Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we easily time function calls in elixir?

How can we easily time function calls in Elixir?

Is there any hidden switch in IEx to enable this?

like image 591
Charles Okwuagwu Avatar asked Apr 16 '15 07:04

Charles Okwuagwu


2 Answers

You can write a module1 that can measure a given function. The following function returns the runtime of a given function in seconds:

defmodule Benchmark do
  def measure(function) do
    function
    |> :timer.tc
    |> elem(0)
    |> Kernel./(1_000_000)
  end
end

Use it like this:

iex> Benchmark.measure(fn -> 123456*654321 end)
9.0e-6

If you want to use that for Benchmarking, then there is another answer.

A better approach than measuring single run execution time is to measure operations per timeframe. This takes the code under test and executes it repeatingly within a given timeframe. This methodology yields more accurate results.

There is a library called Benchwarmer you can use for that:

Add Benchwarmer to your mix.exs

def deps do
  [ { :benchwarmer, "~> 0.0.2" } ]
end

Simply pass an inline function:

iex> Benchwarmer.benchmark fn -> 123456*654321 end
*** #Function<20.90072148/0 in :erl_eval.expr/5> ***
1.2 sec     2M iterations   0.61 μs/op

[%Benchwarmer.Results{...}]
  • [1]: Code taken from http://www.littlelines.com/blog/2014/06/27/elixir-vs-ruby-showdown-part-one/
  • Benchee https://github.com/bencheeorg/benchee
like image 89
Overbryd Avatar answered Oct 17 '22 22:10

Overbryd


This is an answer to a 6 year old question. But I ran into this topic while searching for such a capability and the module suggestion implies one can do:

{time, your_func_result} = :timer.tc(&your_func/arity, [your_func-args])

Thought I would drop that here in case someone else ended up searching for this. After all it's Erlang underneath. So you don't have to define another function in a module etc. time is in microseconds.

like image 36
Sainik Avatar answered Oct 18 '22 00:10

Sainik