gpt4 book ai didi

optimization - 如何有效地迭代 Julia 中的对象列表?

转载 作者:行者123 更新时间:2023-12-03 17:11:28 24 4
gpt4 key购买 nike

我希望这段代码尽可能快地运行。迭代对象列表并更改其字段或使用它们计算某些变量的最有效方法是什么?
这是我的代码:

mutable struct typeA
a::Float64
end

mutable struct typeB
b::Float64
end

mutable struct typeC
c::Float64
end

types = Union{typeA, typeB, typeC}
function change(n::Int64, list::Array{types, 1})
for i = 1:n
j = rand(1:3)
chosen = list[j]
u = rand()
if typeof(chosen) == typeA
if u < chosen.a
chosen.a = u
end
elseif typeof(chosen) == typeB
if u < chosen.b
chosen.b = u
end
elseif typeof(chosen) == typeC
if u > chosen.c
chosen.c = u
end
end
end
list
end

list = Union{types}[typeA(0.7), typeB(0.5), typeC(0.9)]
@time change(10000, list)

这是结果:

0.072776 seconds (85.81 k allocations: 4.694 MiB)

第二次:

0.001378 seconds (4 allocations: 160 bytes)

最佳答案

我明白你想加速内循环部分(不改变一般逻辑)。如果是这种情况,请将 typeof(chosen) == typeA 更改为 typeof(chosen) === typeAchosen isa typeA ( ifelseif 子句中的 typeBtypeC 相同),您应该会看到大约 3 倍的加速。

关于optimization - 如何有效地迭代 Julia 中的对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com