Julia 中使用的函数参数中的美元符号前缀是什么?

What is the dollar-sign prefix in function arguments used for in Julia?

当我在 Julia 中搜索“$”前缀时,我只能找到它用于字符串或表达式插值。例如这里 https://docs.julialang.org/en/v1/base/punctuation/。但是,我看到人们的代码像

add_broadcast!($y_d, $x_d)

如本教程中所述https://cuda.juliagpu.org/stable/tutorials/introduction/. Here the "$" sign cannot be interpolation, can it? There is nothing about such usage in the functions doc either https://docs.julialang.org/en/v1/manual/functions/。所以我很困惑。任何想法表示赞赏。谢谢!

您所展示的 $ 符号表达式是非标准的 Julia 代码,它通常只出现在传递给宏的表达式中。在您的示例中正是这种情况,完整行是:

@btime add_broadcast!($y_d, $x_d)

它使用 BenchmarkTools.jl 中的 @btime 宏。如果您转到 Quick Start 部分,您可以阅读:

If the expression you want to benchmark depends on external variables, you should use $ to "interpolate" them into the benchmark expression to avoid the problems of benchmarking with globals. Essentially, any interpolated variable $x or expression $(...) is "pre-computed" before benchmarking begins:

简而言之,对于 @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)

你可以这样想。在上面的示例中,不使用 $ 就好像您已经创建并 运行 以下函数:

function temp1()
    y = 0
    for _ in 1:10^6
        y += x
    end
    y
end

你得到:

julia> @btime temp1()
  22.106 ms (999489 allocations: 15.25 MiB)
1000000

虽然使用 $ 就像在函数体内定义 x 一样:

function temp2()
    x = 1
    y = 0
    for _ in 1:10^6
        y += x
    end
    y
end

现在你有:

julia> @btime temp2()
  5.000 ns (0 allocations: 0 bytes)
1000000