【发布时间】:2016-01-06 06:07:57
【问题描述】:
我的函数被多次调用并且需要临时数组。而不是每次调用函数时都发生数组分配,我希望临时静态分配一次。
如何在 Julia 中创建具有函数作用域的静态分配数组?
【问题讨论】:
标签: arrays performance static julia allocation
我的函数被多次调用并且需要临时数组。而不是每次调用函数时都发生数组分配,我希望临时静态分配一次。
如何在 Julia 中创建具有函数作用域的静态分配数组?
【问题讨论】:
标签: arrays performance static julia allocation
好的,假设您的函数名为 foo 并带有参数 x,并且您的数组只有 10000 个元素(每个元素都是一个 64 位值),具有一维。然后你可以围绕该函数创建一个范围
let
global foo
let A = Array{Int64}(100)
function foo(x)
# do your tasks
end
end
A 应该是一个 let 变量,因为它会覆盖任何其他全局 A。
【讨论】:
您可以将临时数组包装为类中的引用:
type MyWrapper
thetmparray
thefunction::Function
function MyWrapper(outertmp::Array)
this = new(outertmp)
this.thefunction = function()
#use this.thetmparray or outertmp
end
return this
end
end
这个你可以avoid global variables 并且(将来)有一个每个执行器/线程/进程/机器/等临时数组。
【讨论】:
您可以使用let 块或部分应用程序(对于这种情况,我更喜欢这种方法):
function bind_array(A::Array)
function f(x)
A = A*x
end
end
现在您可以将私有数组绑定到 f 的每个新“实例”:
julia> f_x = bind_array(ones(1,2))
f (generic function with 1 method)
julia> display(f_x(2))
1x2 Array{Float64,2}:
2.0 2.0
julia> display(f_x(3))
1x2 Array{Float64,2}:
6.0 6.0
julia> f_y = bind_array(ones(3,2))
f (generic function with 1 method)
julia> display(f_y(2))
3x2 Array{Float64,2}:
2.0 2.0
2.0 2.0
2.0 2.0
julia> display(f_y(3))
3x2 Array{Float64,2}:
6.0 6.0
6.0 6.0
6.0 6.0
【讨论】: