Nat*_*ong 2 benchmarking elixir
我试图在尝试优化函数之前尝试执行函数.(代码是Elixir,但我正在使用Erlang :timer.tc.)
我的一般方法是"多次运行,然后计算平均持续时间." 但是,当我运行它时,平均值会急剧下降(达到一定程度).
一个例子:
some_func = fn ->
# not my actual function; it's a pure function,
# but exhibits the same speedup
:rand.uniform()
end
run_n_times = fn (count, func) ->
Enum.each(1..count, fn (_i) ->
func.()
end)
end
n = 20
{microseconds, :ok} = :timer.tc(run_n_times, [n, some_func])
IO.puts "#{microseconds / n} microseconds per call (#{microseconds} total for #{n} calls)"
Run Code Online (Sandbox Code Playgroud)
增加值的输出n是这样的(轻度格式化):
174.8 microseconds per call (3496 total for 20 calls )
21.505 microseconds per call (4301 total for 200 calls )
4.5755 microseconds per call (9151 total for 2000 calls )
0.543415 microseconds per call (108683 total for 200000 calls )
0.578474 microseconds per call (578474 total for 1000000 calls )
0.5502955 microseconds per call (1100591 total for 2000000 calls )
0.556457 microseconds per call (2225828 total for 4000000 calls )
0.544754125 microseconds per call (4358033 total for 8000000 calls )
Run Code Online (Sandbox Code Playgroud)
为什么函数运行得越快,我称之为更多,这对基准测试意味着什么?例如,是否有一个经验法则,例如"运行某些东西> = 200k次以进行基准测试"?
由于你的功能非常快(基本上什么都不做),我认为你在这里看到的是设置的开销,而不是函数运行时的任何加速.在这种情况下,在开始运行函数之前,您必须构造一个范围,构造一个匿名函数并调用该Enum.each函数.对于少量重复,这些因素可能对基准的整体运行时间贡献比实际重复更多.