Skip to content

Instantly share code, notes, and snippets.

@odelbos
Created March 19, 2022 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odelbos/5622acd944c082b18eb62f95039011e6 to your computer and use it in GitHub Desktop.
Save odelbos/5622acd944c082b18eb62f95039011e6 to your computer and use it in GitHub Desktop.
Elixir : Measure the execution time of an 'exp'
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
@odelbos
Copy link
Author

odelbos commented Mar 19, 2022

Usage :

duration = Timer.duration :millisecond do
  response = HTTPoison.get "https://...my-site...", [], [timeout: 5000]
end

IO.puts "Request duration: #{duration}ms"

@odelbos
Copy link
Author

odelbos commented Jun 9, 2022

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