问题描述
我想获取Julia中某个函数的执行时间.这是一个最小的工作示例:
I want to obtain the execution time of a function in Julia. Here is a minimum working example:
function raise_to(n)
for i in 1:n
y = (1/7)^n
end
end
如何获取执行raise_to(10)
所需的时间?
How to obtain the time it took to execute raise_to(10)
?
推荐答案
推荐基准测试功能的方法是使用 BenchmarkTools
:
The recommended way to benchmark a function is to use 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
为您做到了.
Note that repeating the computation numerous times (like you did in your example) is a good idea to get more accurate measurements. But BenchmarTools
does it for you.
还请注意,BenchmarkTools
避免了仅使用@time
的许多陷阱.最值得注意的是,使用@time
时,除了运行时间外,您还可能会评估编译时间.这就是为什么@time
的第一次调用经常显示较大的时间/分配的原因:
Also note that BenchmarkTools
avoids many pitfalls of merely using @time
. Most notably with @time
, you're likely to measure compilation time in addition to run time. This is why the first invocation of @time
often displays larger times/allocations:
# 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中函数的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!