我想获取 Julia 中函数的执行时间。这是一个最小的工作示例:
function raise_to(n)
for i in 1:n
y = (1/7)^n
end
end
如何获取执行时间
raise_to(10)
?
最佳答案
对函数进行基准测试的推荐方法是使用 BenchmarkTools
:
julia> function raise_to(n)
y = (1/7)^n
end
raise_to (generic function with 1 method)
julia> using BenchmarkTools
julia> @btime raise_to(10)
1.815 ns (0 allocations: 0 bytes)
请注意,多次重复计算(就像您在示例中所做的那样)是获得更准确测量值的好主意。但是
BenchmarTools
为你做。另请注意
BenchmarkTools
避免了仅使用 @time
的许多陷阱.最值得注意的是 @time
,除了运行时间之外,您可能还会测量编译时间。这就是为什么第一次调用 @time
经常显示更大的时间/分配:# First invocation: the method gets compiled
# Large resource consumption
julia> @time raise_to(10)
0.007901 seconds (7.70 k allocations: 475.745 KiB)
3.5401331746414338e-9
# Subsequent invocations: stable and low timings
julia> @time raise_to(10)
0.000003 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9
julia> @time raise_to(10)
0.000002 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9
julia> @time raise_to(10)
0.000001 seconds (5 allocations: 176 bytes)
3.5401331746414338e-9
关于julia - 如何在 Julia 中获取函数的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60867667/