我想在Julia中获得一个函数的执行时间。下面是一个最小的工作示例:
function raise_to(n)
for i in 1:n
y = (1/7)^n
end
end
如何获取执行raise_to(10)
所需的时间?
发布于 2020-03-26 21:10:05
建议对函数进行基准测试的方法是使用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
发布于 2020-03-27 03:18:56
@time
@time
的工作原理与前面的答案中提到的一样,但如果是第一次在julia会话中调用该函数,它将包含编译时间。
@btime
如果在代码中放入using BenchmarkTools
,也可以使用@btime
。
https://github.com/JuliaCI/BenchmarkTools.jl
这将在初始编译运行后多次重新运行函数,然后平均时间。
julia> using BenchmarkTools
julia> @btime sin(x) setup=(x=rand())
4.361 ns (0 allocations: 0 bytes)
0.49587200950472454
@timeit
另一个非常有用的性能分析库是TimerOutputs.jl
https://github.com/KristofferC/TimerOutputs.jl
using TimerOutputs
# Time a section code with the label "sleep" to the `TimerOutput` named "to"
@timeit to "sleep" sleep(0.02)
# ... several more calls to @timeit
print_timer(to::TimerOutput)
──────────────────────────────────────────────────────────────────────
Time Allocations
────────────────────── ───────────────────────
Tot / % measured: 5.09s / 56.0% 106MiB / 74.6%
Section ncalls time %tot avg alloc %tot avg
──────────────────────────────────────────────────────────────────────
sleep 101 1.17s 41.2% 11.6ms 1.48MiB 1.88% 15.0KiB
nest 2 1 703ms 24.6% 703ms 2.38KiB 0.00% 2.38KiB
level 2.2 1 402ms 14.1% 402ms 368B 0.00% 368.0B
level 2.1 1 301ms 10.6% 301ms 368B 0.00% 368.0B
throwing 1 502ms 17.6% 502ms 384B 0.00% 384.0B
nest 1 1 396ms 13.9% 396ms 5.11KiB 0.01% 5.11KiB
level 2.2 1 201ms 7.06% 201ms 368B 0.00% 368.0B
level 2.1 3 93.5ms 3.28% 31.2ms 1.08KiB 0.00% 368.0B
randoms 1 77.5ms 2.72% 77.5ms 77.3MiB 98.1% 77.3MiB
funcdef 1 2.66μs 0.00% 2.66μs - 0.00% -
──────────────────────────────────────────────────────────────────────
宏可以具有begin
... end
在这些函数的文档中可以看到,它们可以涵盖多个语句或函数。
@my_macro begin
statement1
statement2
# ...
statement3
end
希望这能有所帮助。
发布于 2020-03-26 20:48:43
@time
宏可用于告诉您计算函数所用的时间。它还给出了内存是如何分配的。
julia> function raise_to(n)
for i in 1:n
y = (1/7)^n
end
end
raise_to (generic function with 1 method)
julia> @time raise_to(10)
0.093018 seconds (26.00 k allocations: 1.461 MiB)
https://stackoverflow.com/questions/60867667
复制相似问题