Created
March 19, 2022 12:30
-
-
Save odelbos/5622acd944c082b18eb62f95039011e6 to your computer and use it in GitHub Desktop.
Elixir : Measure the execution time of an 'exp'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Timer do | |
@moduledoc """ | |
Helper module to measure the execution time of an 'exp' | |
""" | |
@doc """ | |
Measure the execution time of 'exp'. | |
## Parameters | |
- unit: :second | :millisecond | :microsecond | :nanosecond | :native | |
""" | |
defmacro duration(unit, do: exp) do | |
quote do | |
t1 = :os.system_time unquote(unit) | |
unquote(exp) | |
t2 = :os.system_time unquote(unit) | |
t2 - t1 | |
end | |
end | |
end |
Also, using the :timer
module
{us, :ok} = :timer.tc(IO, :puts, ["Hello World"])
# us : in microseconds (divide by 1_000_000 to get seconds)
:timer.tc(IO, :puts, ["Hello World"])
# {22, :ok}
add = fn (x, y) -> x + y end
:timer.tc(add, [1,3])
# {5, 4}
:timer.tc(fn ->
# ...
:ok
end)
# {1_302_342, :ok}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage :