当我在 Julia 中搜索“$”前缀时,我能找到的只是它用于字符串或表达式插值。例如,这里https://docs.julialang.org/en/v1/base/punctuation/。但是,我见过人们的代码,例如
add_broadcast!($y_d, $x_d)
Run Code Online (Sandbox Code Playgroud)
在本教程https://cuda.juliagpu.org/stable/tutorials/introduction/ 中。这里的“$”符号不能插值,可以吗?函数文档中没有关于这种用法的任何内容https://docs.julialang.org/en/v1/manual/functions/。所以我很困惑。任何想法表示赞赏。谢谢!
Bog*_*ski 11
您显示的符号表达式$
是非标准 Julia 代码,它通常仅出现在传递给宏的表达式中。这正是您的示例中的情况,其中整行是:
@btime add_broadcast!($y_d, $x_d)
Run Code Online (Sandbox Code Playgroud)
它使用@btime
BenchmarkTools.jl 中的宏。如果您转到“快速入门”部分,您可以阅读:
如果要进行基准测试的表达式依赖于外部变量,则应该使用 $ 将它们“插入”到基准表达式中,以避免使用全局变量进行基准测试的问题。本质上,任何插值变量 $x 或表达式 $(...) 在基准测试开始之前都是“预先计算的”:
简而言之,@btime
您可以将$
它们“插入”到基准测试表达式中,以获得正确的基准测试结果。
该$
符号与宏一起使用,也可以在其他包中进行插值,例如 DataFrameMacros.jl。
编辑:
$
引用非常量全局变量时不使用如何影响执行时间的示例:
julia> using BenchmarkTools
julia> x = 1
1
julia> @btime (y = 0; for _ in 1:10^6 y += x end; y) # slow and a lot of allocations
22.102 ms (999489 allocations: 15.25 MiB)
1000000
julia> @btime (y = 0; for _ in 1:10^6 y += $x end; y) # loop is optimized out
5.600 ns (0 allocations: 0 bytes)
1000000
julia> const z = 1
1
julia> @btime (y = 0; for _ in 1:10^6 y += z end; y) # loop is optimized out
5.000 ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)
你可以这样想。在上面的示例中,不使用$
就好像您已经创建并运行了以下函数:
function temp1()
y = 0
for _ in 1:10^6
y += x
end
y
end
Run Code Online (Sandbox Code Playgroud)
你得到:
julia> @btime temp1()
22.106 ms (999489 allocations: 15.25 MiB)
1000000
Run Code Online (Sandbox Code Playgroud)
而 using$
就好像x
在函数体内定义一样,如下所示:
function temp2()
x = 1
y = 0
for _ in 1:10^6
y += x
end
y
end
Run Code Online (Sandbox Code Playgroud)
现在你有:
julia> @btime temp2()
5.000 ns (0 allocations: 0 bytes)
1000000
Run Code Online (Sandbox Code Playgroud)