一个宏总是比julia中的函数更快吗?

Til*_*ill 0 julia

我有兴趣传递一个简单函数的值(在下面的最小例子中为2).我的最小例子表明宏比函数快得多.这是对的还是我犯了错误?

using BenchmarkTools
macro func!(arg)
    arg = eval(arg)
    for i in 1:length(arg)
        arg[i] = 2
    end
    return nothing
end
function func!(arg)
    for i in 1:length(arg)
        arg[i] = 2
    end
    return nothing
end
x = ones(10^3)
@btime @func!(x) --> 0.001 ns (0 allocations: 0 bytes)
@btime func!(x) --> 332.272 ns (0 allocations: 0 bytes)
Run Code Online (Sandbox Code Playgroud)

EDIT1:

不,它不快.似乎@btime和@time宏不适用于宏.我在下面的最小例子中用@time宏检查了它.我计算了宏的秒数,即使@time告诉我几乎没有时间.

x = ones(10^7)
@time @func!(x) --> 0.000001 seconds (3 allocations: 144 bytes)
@time func!(x) --> 0.007362 seconds (4 allocations: 160 bytes)
Run Code Online (Sandbox Code Playgroud)

Bog*_*ski 6

上次有两条评论.

宏实际上更慢

请考虑此代码,该代码评估宏和函数完成其工作所需的实际时间:

julia> x = ones(10^8);

julia> t1 = time_ns()
0x00006937ba4da19e

julia> @func!(x)

julia> t2 = time_ns()
0x00006939ebcb5c41

julia> Int(t2 - t1)
9420257955

julia>

julia> x = ones(10^8);

julia> t1 = time_ns()
0x0000693a0ee9452f

julia> func!(x)

julia> t2 = time_ns()
0x0000693a16ea941e

julia> Int(t2 - t1)
134303471
Run Code Online (Sandbox Code Playgroud)

而且你看到该功能明显更快.区别在于时间在不同时刻消耗(编译时间与运行时间和@btime测量运行时间).

仅当宏的参数在全局范围内定义时,该宏才起作用

例如,以下代码失败:

julia> function test()
           abc = [1,2,3]
           @func!(abc)
           abc
       end
ERROR: LoadError: UndefVarError: abc not defined
Run Code Online (Sandbox Code Playgroud)

而:

julia> function test()
           abc = [1,2,3]
           func!(abc)
           abc
       end
test (generic function with 1 method)

julia> test()
3-element Array{Int64,1}:
 2
 2
 2
Run Code Online (Sandbox Code Playgroud)

所以函数和宏实际上做了不同的事情.

一般来说,我通常建议不要使用宏,除非有充分的理由这样做.