## 一个宏总是比julia中的函数更快吗？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (1)
• 关注 (0)
• 查看 (102)

``````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)
``````

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

### 宏实际上更慢

``````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
``````

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

``````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
``````