可以使用元组将多个变量绑定到一个变量上,然后将该变量传递给setup函数。例如:
using BenchmarkTools
# 原始代码
function my_setup()
a = rand(1000)
b = rand(1000)
c = rand(1000)
return a, b, c
end
function my_func(x)
return sum(x[1]) + sum(x[2]) + sum(x[3])
end
@benchmark my_func(my_setup()...)
# Warmup...
# BenchmarkTools.Trial:
# memory estimate: 8.00 KiB
# allocs estimate: 2
# --------------
# minimum time: 30.300 μs (0.00% GC)
# median time: 32.101 μs (0.00% GC)
# mean time: 35.070 μs (3.59% GC)
# maximum time: 2.332 ms (96.95% GC)
# --------------
# samples: 10000
# evals/sample: 1
可以改写为:
function my_setup()
x = (rand(1000), rand(1000), rand(1000))
return x
end
function my_func(x)
return sum(x[1]) + sum(x[2]) + sum(x[3])
end
@benchmark my_func(my_setup()...)
# Warmup...
# BenchmarkTools.Trial:
# memory estimate: 8.00 KiB
# allocs estimate: 2
# --------------
# minimum time: 30.300 μs (0.00% GC)
# median time: 32.101 μs (0.00% GC)
# mean time: 35.070 μs (3.59% GC)
# maximum time: 2.332 ms (96.95% GC)
# --------------
# samples: 10000
# evals/sample: 1
在这个例子中,我们将a、b、c三个变量绑定到元组x上,并将x作为参数传递给my_func函数。这样就不需要在my_func函数中访问多个变量了。