访问struct时如何避免分配?朱莉娅

问题描述 投票:0回答:1

我正在尝试我的函数调用尽可能少的内存分配,以使其运行更快。问题是,当我访问作为参数给出的结构时,似乎有很多分配。

function mCondition(y,t,integrator)
    xp, yp, zp, vx, vy, vz = y
    mu = integrator.p[1]
    cond = (xp - 1.0 + mu)*vx +  yp*vy + zp*vz
    return cond
end
struct myStr
    p
    u
end

y = rand(6)
t = 0.0
A = myStr([0.01215],rand(6))

#test call
mCondition(y,t,A)

using BenchmarkTools
@btime mCondition(y,t,A)

输出是:

julia> @btime mCondition(y,t,A)
  102.757 ns (9 allocations: 144 bytes)
-0.07935578340713843

我认为问题出在struct上,因为当我删除那部分代码时,

function mCondition(y,t,integrator)
    xp, yp, zp, vx, vy, vz = y
    cond = (xp - 1.0)*vx +  yp*vy + zp*vz
    return cond
end

这是基准测试的结果:

julia> @btime mCondition(y,t,A)
  18.294 ns (1 allocation: 16 bytes)
-0.08427348469961408

这更接近我对函数内部的期望(但我仍然想知道这个分配是否必要)。如果你能帮我理解发生的事情,甚至修复它会很好。

提前致谢 :)

memory-management julia
1个回答
-1
投票

您需要在struct中键入注释字段定义,以使编译器能够生成高性能代码。在struct字段中没有类型注释,编译器无法在编译时推断字段的类型,这会使决策停留在运行时,因此这会损害性能并导致不必要的分配。

那么解决方案是,

struct myStr
    p::Vector{Float64}
    u::Vector{Float64}
end

例如,如果您希望它与其他类型的structs一起使用,您也可以使Vector参数化。有关更多信息,请参阅文档的Types部分。

我还建议您阅读文档的Performance Tips部分,以了解有关如何在Julia中编写高性能代码的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.