gpt4 book ai didi

parameter-passing - 将参数传递给函数而不在 JULIA-LANG 中复制它们

转载 作者:行者123 更新时间:2023-12-01 07:51:24 25 4
gpt4 key购买 nike

假设我需要创建一个巨大的数组并在我的另一个函数中的程序中使用它。我想这样做而不在每次使用它时复制这个数组。我知道如果我简单地将它们作为参数,Julia 有一个共享调用机制,它不会复制参数。但是,如果我执行以下操作,它是否仍然能够在每次循环中不创建副本的情况下运行?:

function main()
huge_arr = ones(Float32,20000,30000)
another_arr = rand(4,5)
coupled_var = (huge_arr,another_arr)
for i=1:100
target_function(coupled_var)
end
end

function target_function(x)
my_first_var = x[1]
my_second_var = x[2]
# some operations here
end

最佳答案

您正在操作 的数组可变 对象(声明为 mutable struct Array{...} ... ),因此通过引用语义传递。

function target_function(x)
my_first_var = x[1] # x[1],x[2] are _mutable_ objects
my_second_var = x[2] # -> this only create a new binding (no copy)
# some operations here
end

您可以查看 my_first_varx[1]使用 pointer_from_objref 指向同一个对象.

例子:
function foo(x) 
y = x
println("Check ptr $(pointer_from_objref(x) == pointer_from_objref(y)) x:$(pointer_from_objref(x)) y:$(pointer_from_objref(y))")
end

然后尝试:
x=4.5
foo(x)
Check ptr false x:Ptr{Void} @0x00007f25a28a2850 y:Ptr{Void} @0x00007f25a28a2860

-> 对于 Float64 , y=x 执行 复制
x=rand(5)
foo(x)
Check ptr true x:Ptr{Void} @0x00007f25a284a410 y:Ptr{Void} @0x00007f25a284a410

-> 对于数组,y=x 执行 复制(共享相同的内存地址)

注意:在您的 target_function注意使用组件级操作,例如 my_first_var .*= 2因为类似 my_first_var *= 2 创建一个新变量 .

例如:
julia> pointer_from_objref(x)
Ptr{Void} @0x00007f25a043f890 <-
|
julia> x *= 2 |
5-element Array{Float64,1}:
3.81254
3.60607
2.86026
1.94396
2.91994 different memory
|
julia> pointer_from_objref(x) |
Ptr{Void} @0x00007f25a0afa210 <--|
|
julia> x .*= 2
5-element Array{Float64,1}:
7.62507
7.21214
5.72052
3.88793
5.83987 same memory
|
julia> pointer_from_objref(x) |
Ptr{Void} @0x00007f25a0afa210 <--|

关于parameter-passing - 将参数传递给函数而不在 JULIA-LANG 中复制它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48781821/

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