gpt4 book ai didi

memory-management - 在 Julia 中释放内存

转载 作者:行者123 更新时间:2023-12-05 00:18:17 24 4
gpt4 key购买 nike

我试图在 julia 中释放内存,但没有成功。

function memuse()
return string(round(Int,parse(Int,readall(`ps -p 29563 -o rss=`))/1024),"M")
end


function test()
for i = 1:2 println("\ni=$i")
a = rand(10000,10000)
println("Created a $(memuse())")
a = 0
gc()
println("Release a $(memuse())\n")

b = rand(10000,10000)
println("Created b $(memuse())")
b = 0
gc()
println("Release b $(memuse())\n")

c = rand(10000,10000)
println("Created c $(memuse())")
c =0
gc()
println("Release c $(memuse())\n")
end
end

输出:
i=1
Created a 918M
Release a 918M

Created b 1681M
Release b 1681M

Created c 2444M
Release c 2444M


i=2
Created a 3207M
Release a 2444M

Created b 3207M
Release b 2444M

Created c 3207M
Release c 2444M

这段代码只需要 918M 即可运行,但使用了 3207M。

问题:
为什么 gc() 不释放未使用的内存?
有什么方法可以强制垃圾收集器释放?
为什么垃圾收集器只在第二次迭代时释放一些内存?

最佳答案

来自 JeffBezanson 在此 GitHub Issue

Yes this has to do with how code is generated. The rand call comes down to rand!(Array(T, dims)), and the inner Array remains on the "argument stack", since those slots generally get reused. It would be good to null out those slots in a case like this, but it has to be done very carefully to avoid adding lots of unnecessary stores.



你可以这样解决:
@noinline function wrap()
rand(10000,10000)
end

function test()
for i = 1:2 println("\ni=$i")
a = wrap()
println("Created a $(memuse())")
a = 0
gc()
println("Release a $(memuse())\n")

b = wrap()
println("Created b $(memuse())")
b = 0
gc()
println("Release b $(memuse())\n")

c = wrap()
println("Created c $(memuse())")
c =0
gc()
println("Release c $(memuse())\n")

end
end

请注意 @noinline以便清空堆栈。

关于memory-management - 在 Julia 中释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38254844/

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