【发布时间】:2021-09-23 09:44:15
【问题描述】:
我有两个问题,我会写在这篇文章的底部。
背景
我使用TimerOutputs.jl 包测量了时间,我发现了难以理解的行为。
我编写了名为f的函数,并测量了以下4个部分:whole in,i section,x section,whole out。
代码和结果如下:
[输入1]
using TimerOutputs
const to = TimerOutput()
f = function()
@timeit to "whole in" begin
a = [];
@timeit to "i section" begin
for i in 1:1000
push!(a,randn(5,5))
end
end
@timeit to "x section" begin
for x in 1:1000
push!(a,randn(5,5) .+ x )
end
end
end
end
@timeit to "whole out" f()
show(to)
[输出1]
────────────────────────────────────────────────────────────────────────
Time Allocations
────────────────────── ───────────────────────
Tot / % measured: 106ms / 95.8% 12.0MiB / 99.4%
Section ncalls time %tot avg alloc %tot avg
────────────────────────────────────────────────────────────────────────
whole out 1 102ms 100% 102ms 11.9MiB 100% 11.9MiB
whole in 1 310μs 0.30% 310μs 878KiB 7.18% 878KiB
x section 1 155μs 0.15% 155μs 579KiB 4.73% 579KiB
i section 1 151μs 0.15% 151μs 298KiB 2.43% 298KiB
────────────────────────────────────────────────────────────────────────
[输入 2]
TimerOutputs.time(to["whole out"])/TimerOutputs.time(to["whole out"]["whole in"])
[输出2]
328.0928134063809
问题
第一季度:
为什么运行whole out的时间比运行whole in的时间长328倍?
我猜这种差异来自调用函数时 CPU 和内存的行为机制,但我没有任何知识。我要说清楚。
第二季度:
我想测量运行f 的时间并在f 中使用结果(whole out 的@timeit 的输出)。我该怎么做?
任何信息将不胜感激。
【问题讨论】:
-
一些 cmets:(1) 为了避免测量预编译时间,正如答案中提到的可能是你所看到的,你可能宁愿使用 BenchmarkTools.jl 中的 @benchmark 之类的东西。 (2)如果你关心性能的程度,你关心细节的时间,你可能不应该使用
push!,如果可能的话。而是预先分配并就地填充(或者至少给push!一个sizehint!使用)。
标签: time timer jupyter-notebook julia