我有一个简单的问题。我已经定义了一个结构,我需要启动很多(以数百万计)它们并循环它们。
我一次启动一个并按如下方式进行循环:
using Distributions
mutable struct help_me{Z<:Bool}
can_you_help_me::Z
millions_of_thanks::Z
end
for i in 1:max_iter
tmp_help = help_me(rand(Bernoulli(0.5),1)[1],rand(Bernoulli(0.99),1)[1])
# many follow-up processes
end
Run Code Online (Sandbox Code Playgroud)
内存分配在max_iter中按比例增加。出于我的目的,我不需要保存每个结构。有没有办法“重用”结构使用的内存分配?
你的主要问题在于:
rand(Bernoulli(0.5),1)[1], rand(Bernoulli(0.99),1)[1]
Run Code Online (Sandbox Code Playgroud)
您正在创建一个长度为 1 的数组,然后从该数组中读取第一个元素。这会分配不必要的内存并且需要时间。不要在这里创建数组。相反,写
rand(Bernoulli(0.5)), rand(Bernoulli(0.99))
Run Code Online (Sandbox Code Playgroud)
这只会创建随机标量,而不是数组。
在这里比较时间:
julia> using BenchmarkTools
julia> @btime rand(Bernoulli(0.5),1)[1]
36.290 ns (1 allocation: 96 bytes)
false
julia> @btime rand(Bernoulli(0.5))
6.708 ns (0 allocations: 0 bytes)
false
Run Code Online (Sandbox Code Playgroud)
速度提高 6 倍,且无需内存分配。
This seems to be a general issue. Very often I see people writing rand(1)[1], when they should be using just rand().
Also, consider whether you actually need to make the struct mutable, as others have mentioned.