Durex (durex v0.3.0)

Parse durations, such as "1s", to its numerical millisecond value, e.g. 1_000, so you can do things such as:

"1s"
|> Durex.ms!()
|> Process.sleep()

Examples

iex> Durex.ms "3s"
{:ok, 3_000}

iex> Durex.ms "1h"
{:ok, 3600_000}

# Works with float too
iex> Durex.ms "0.5s"
{:ok, 500}

iex> Durex.ms "1.5h"
{:ok, 5400_000}

# Cannot ms duration less than 1ms | 1.0ms
iex> Durex.ms "0.5ms"
:error

# Fractional durations in ms will be truncated
iex> Durex.ms "1.5ms"
{:ok, 1}

Of course, there is also the bang version ms!/1:

# Bang version available
iex> Durex.ms! "3s"
3_000

Supported units

  • ms (for millisecond)
  • s (for second)
  • m (for minute)
  • h (for hour)
  • d (for days)
  • w (for week)

Performance Notes

  • Parsing durations which include integers is about 4x faster than their version containing floats. So instead of parsing "0.5s", use "500ms" for maximum performance.

  • To benchmark, run: $ mix run bench/ms.exs

Link to this section Summary

Functions

Parse duration as milliseconds

Parse duration but raise if it fails

Link to this section Types

Specs

duration() :: bitstring()

Link to this section Functions

Specs

ms(duration()) :: {:ok, pos_integer()} | :error

Parse duration as milliseconds

Specs

ms!(duration()) :: pos_integer()

Parse duration but raise if it fails