考虑这个函数
function test_function(state, M, new_number)
M[state..., 1] = new_number
end
在我的程序中,我想多次运行此函数,每次参数都是新的(有时由用户提供)。
为了测试这个函数的内存分配和速度,我写了这个循环
function test_for_loop(loop_num)
state = [1, 1, 1 ]
M = randn(10,10,10,10)
new_number = 3.0
for i in 1:loop_num
test_function(state, M, new_number)
end
end
注意test_for_loop
纯粹是为了测试效率而编写的test_function
被多次应用。事实上,在每个应用程序中,state
, M
, and new_number
是事先不知道的。
I used @allocated
找到内存分配。随着我的增加loop_num
,内存分配上升。我不知道为什么所以我用了--track-allocation
。事实证明M[state...] = new_number
占用大量内存分配。有人可以解释一下为什么吗?为什么它分配额外的内存,以及如何减少内存分配,使其不会随着loop_num
?
原因是:
state = [1, 1, 1]
这是一个向量,它没有指定它的类型有多长。
将其更改为例如一个元组(因为元组已知编译时大小):
state = (1, 1, 1)
分配问题将得到解决:
julia> function test_for_loop(loop_num)
state = (1, 1, 1)
M = randn(10,10,10,10)
new_number = 3.0
for i in 1:loop_num
test_function(state, M, new_number)
end
end
test_for_loop (generic function with 1 method)
julia> @time test_for_loop(10^8)
0.118755 seconds (2 allocations: 78.188 KiB)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)