作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在尝试优化函数之前对其执行进行计时。 (代码是 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)"
增加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 )
为什么一个函数运行得越快,我调用它的次数越多,这对基准测试意味着什么?例如,是否有一个经验法则,例如“运行某项 >= 200k 次以进行基准测试” “?
最佳答案
由于您的函数非常快(基本上什么也不做),我认为您在这里看到的是设置的开销,而不是函数运行时的任何加速。在这种情况下,在开始运行函数之前,您必须构造一个范围、构造一个匿名函数并调用 Enum.each 函数。对于少量重复,这些因素对基准测试总体运行时间的影响可能比实际重复更大。
关于benchmarking - 为什么一个函数调用的次数越多,运行得越快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36033190/
我是一名优秀的程序员,十分优秀!