在julia中连接数组时,是否有一种避免内存分配的方法?例如,
const x = [1.0,2.0,3.0]
我预分配
y = zeros(3,3)
然后获得新的y
y = hcat(x,x,x)
BenchmarkTools.Trial:
memory estimate: 256 bytes
allocs estimate: 4
--------------
minimum time: 62.441 ns (0.00% GC)
median time: 68.445 ns (0.00% GC)
mean time: 98.795 ns (18.76% GC)
maximum time: 40.485 μs (99.71% GC)
--------------
samples: 10000
evals/sample: 987
那我该如何避免分配?
答案 0 :(得分:2)
julia> using BenchmarkTools
julia> const y = zeros(3,3);
julia> const x = [1.0,2.0,3.0];
julia> @benchmark y[1:3,:] .= x
BenchmarkTools.Trial:
memory estimate: 64 bytes
allocs estimate: 1
--------------
minimum time: 17.066 ns (0.00% GC)
median time: 20.480 ns (0.00% GC)
mean time: 30.749 ns (24.95% GC)
maximum time: 38.536 μs (99.93% GC)
--------------
samples: 10000
evals/sample: 1000
julia> y
3×3 Array{Float64,2}:
1.0 1.0 1.0
2.0 2.0 2.0
3.0 3.0 3.0
或者您可以遍历行-对于单行调用,将不会进行分配:
julia> @benchmark y[1,:] = x
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 12.373 ns (0.00% GC)
median time: 12.800 ns (0.00% GC)
mean time: 13.468 ns (0.00% GC)
maximum time: 197.547 ns (0.00% GC)
--------------
samples: 10000
evals/sample: 1000