理解Julia的内存分配



我正在尝试理解Julia中的内存分配,并在玩以下测试代码:

function f()
function test(x,y)
return x-1,y+1
end
x1=5
y1=6
function stest(num_runs,x,y)
for i in 1:num_runs
x,y=test(x,y)
end
return x,y
end
x1,y1=stest(10,x1,y1)
println(x1,' ',y1)
end
@time begin
f()
end
@time begin
f()
end

当我运行它时,我得到以下输出:

-5 16
0.027611 seconds (20.59 k allocations: 1.039 MiB, 92.11% compilation time)
-5 16
0.000077 seconds (18 allocations: 496 bytes)

为什么会有内存分配?为什么第一次这么多?我一直在通读这些文件,但很难弄清楚。

第一次,几乎所有的分配都来自编译。第二次,分配都来自打印。

尝试使用BenchmarkTools。通过这种方式,您将避免测量用于编译代码的时间和内存(通常对运行时而不是编译时间感兴趣(。但是,此工具会多次运行基准测试,因此您需要注释掉println行。

julia> using BenchmarkTools
julia> @benchmark f()
BenchmarkTools.Trial: 10000 samples with 1000 evaluations.
Range (min … max):  1.700 ns … 48.500 ns  ┊ GC (min … max): 0.00% … 0.00%
Time  (median):     2.000 ns              ┊ GC (median):    0.00%
Time  (mean ± σ):   1.971 ns ±  0.520 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%
▂       █
▄▁▁▁▁▁▁▁▄▁▁▁▁▁▁▁█▁▁▁▁▁▁▁█▁▁▁▁▁▁▁▁▃▁▁▁▁▁▁▁▃▁▁▁▁▁▁▁▂▁▁▁▁▁▁▁▂ ▂
1.7 ns         Histogram: frequency by time         2.4 ns <
Memory estimate: 0 bytes, allocs estimate: 0.

打印分配内存。如果你在打印的地方注释一行,你会看到你想要的:

0.000001 seconds
0.000001 seconds

最新更新