在julia中,宏是否总是比函数快?

时间:2018-09-27 20:49:04

标签: 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)

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)

1 个答案:

答案 0 :(得分: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

您会看到该功能明显更快。区别在于时间是在不同的时间消耗的(编译时间与运行时间,@btime测量运行时间)。

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

例如,以下代码失败:

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

同时:

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

所以函数和宏实际上有不同的作用。

通常,除非有充分的理由,否则我通常建议不要使用宏。