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

标签 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

关于julia - 在 julia 中使用 vcat 时避免内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53507204/

相关文章:

julia - 获取函数签名

Julia:BigFloat 正态分布

python - 具有多个根的编程语言

function - 在 Julia 的 for 循环中索引函数的名称

julia - 如何在调用 Reduce 包中的集成命令时使用符号表达式

julia - 返回 Julia 中二维直方图箱中的频率

julia - 从 Julia 中的 Nullable 类型转换

python - Julia 的范围内是否有 skip 参数?

julia - Julia 中的特征向量——结果不如 Mathematica 精确

julia - 如果值为正则打印额外的空格