Memory management 访问结构时如何避免分配?朱莉娅

Memory management 访问结构时如何避免分配?朱莉娅,memory-management,julia,Memory Management,Julia,我正在尝试我的函数调用拥有尽可能少的内存分配,以使它运行得更快。问题是,当我访问作为参数给出的结构时,似乎有很多分配 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

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

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
我认为问题在于结构,因为当我删除这部分代码时

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
这更接近于我对函数内部发生的事情的预期(但我仍然怀疑这种分配是否必要)。如果你能帮助我了解发生了什么,甚至修复它,那就太好了


提前感谢:)

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

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)
那么解决办法是,

struct myStr
    p::Vector{Float64}
    u::Vector{Float64}
end
例如,如果希望使用其他类型的
Vector
s,也可以将
struct
参数化。有关更多信息,请参阅文档部分


我还建议您阅读文档部分,以了解如何在Julia中编写高性能代码。

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

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)
那么解决办法是,

struct myStr
    p::Vector{Float64}
    u::Vector{Float64}
end
例如,如果希望使用其他类型的
Vector
s,也可以将
struct
参数化。有关更多信息,请参阅文档部分


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

谢谢,这真的很有帮助。我真的需要学习更多,我会继续阅读文档。谢谢,这真的很有帮助。我真的需要学习更多,我会继续阅读文档。