Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

timing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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{...}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...