gpt4 book ai didi

import - 在 Julia 中创建共享模块的推荐方法是什么?

转载 作者:行者123 更新时间:2023-12-04 14:03:12 24 4
gpt4 key购买 nike

经过一些实验和搜索,我找到了两种创建共享模块的方法具有一些常量值。

方案A:

# in file sharedconstants.jl:
module sharedconstants
kelvin = 273.15
end
# -------------------------


# in file main.jl:
include("./sharedconstants.jl");
using .sharedconstants
print(sharedconstants.kelvin, "\n");
# -------------------------

方案 B:

# in file sharedconstants.jl:
module sharedconstants
kelvin = 273.15
end
# -------------------------


# in file main.jl:
import sharedconstants
print(sharedconstants.kelvin, "\n");
# -------------------------

方案 B 并不总是有效,当它失败时它会抛出在当前路径中找不到共享常量的错误。另外,方案B要求模块名称(sharedconstants)与主干相同文件名。我想知道以上哪种方式更好编译和执行。还有其他方法可以完成这项工作吗?我是从 FORTRAN 转过来的,我很习惯简单地在我的代码中使用 sharedconstants

最佳答案

出于性能原因,这应该是一个const(BTW 模块名称使用 CamelNaming):

module SharedConstants2
const kelvin = 273.15
end

以这种方式编写它可以使其类型稳定,从而导致巨大的性能差异:


julia> @btime sharedconstants.kelvin * 3
18.574 ns (1 allocation: 16 bytes)
819.4499999999999

julia> @btime SharedConstants2.kelvin * 3
0.001 ns (0 allocations: 0 bytes)
819.4499999999999

关于“放在哪里”这个问题,我建议做一个 Julia 包——从这里开始阅读:https://pkgdocs.julialang.org/v1/creating-packages/

最后,您可能会看一下 PhysicalConstants.jlhttps://github.com/JuliaPhysics/PhysicalConstants.jl

关于import - 在 Julia 中创建共享模块的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69335757/

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