在julia中使用vcat时避免内存分配

  • 本文关键字:内存 分配 vcat julia julia
  • 更新时间 :
  • 英文 :


在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

那么我该如何避免分配呢?

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

最新更新