我们如何轻松地在灵药中调用函数调用? [英] How can we easily time function calls in elixir?
问题描述
在IEx中有没有隐藏的开关可以使用 time 你可以编写一个可以测量给定函数的模块 1 。
以下函数以秒为单位返回给定函数的运行时间: defmodule基准do
def measure(函数)do
函数
|> :timer.tc
|> elem(0)
|> Kernel./(1_000_000)
end
end
像这样使用它:
iex> Benchmark.measure(fn - > 123456 * 654321结束)
9.0e-6
如果您想将其用于基准测试,那么还有另一个答案。
比测量单次执行时间更好的方法是测量每个时间段的操作。这需要测试代码并在给定时间范围内重复执行。这种方法可以产生更准确的结果。
有一个库称为 Benchwarmer ,您可以使用它:
将Benchwarmer添加到您的 mix.exs
def deps do
[{:benchwarmer,〜> 0.0.2}]
end
只需传递一个内联函数即可:
IEX> Benchwarmer.benchmark fn - > 123456 * 654321 end
***#Function< 20.90072148 / 0 in:erl_eval.expr / 5> ***
1.2秒2M迭代0.61μs/ op
[%Benchwarmer.Results {...}]
- [1]:取自 http://www.littlelines.com/blog/2014/06/27/elixir-vs-ruby-showdown-part-one/
- 名为Benchfella的另一个Benchmarking库 https://github.com/ alco / benchfella
How can we easily time function calls in Elixir?
Is there any hidden switch in IEx to enable this?
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/
- Another Benchmarking library called Benchfella https://github.com/alco/benchfella
这篇关于我们如何轻松地在灵药中调用函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!