Muhammad Lukman Low
Muhammad Lukman Low

Reputation: 8533

Is there an equivalent module of python's timeit in Elixir?

In python you can time small pieces of execution time of code using the timeit module.

https://docs.python.org/2/library/timeit.html

Is there an equivalent in Elixir ?

Upvotes: 4

Views: 1007

Answers (1)

bitwalker
bitwalker

Reputation: 9261

The simplest tool would be to use Erlang's :timer module, with one of it's tc variants. It returns execution time in microseconds and the result of the function as a tuple. To time an anonymous function you can do

{time, res} = :timer.tc fn -> :timer.sleep(1000) end
# {1000575, :ok}

{time, res} = :timer.tc(fn(ms) -> :timer.sleep(ms) end, [1000])
# {1001283, :ok}

To time a module function you can do

defmodule Sleepy do
  def sleep(ms) do
    :timer.sleep(ms)
  end
end

{time, res} = :timer.tc(&Sleepy.sleep/1, [1000])
# {1001106, :ok}

{time, res} = :timer.tc(Sleepy, :sleep, [1000])
# {1000352, :ok}

Timex is another option, which has a friendlier API for measuring times, amongst other things, however if all you need is to time something, :timer is more than sufficient with a bit of wrapper code.

Upvotes: 8

Related Questions