我编写了两个简单的函数,定义如下
function test1(var1::Float64)
for i = 1:1e7
sin(var1)*cos(var1)
end
end
function test2(var1::Float64)
cs = cos(var1)
ss = sin(var1)
for i = 1:1e7
ss*cs
end
end
第一个函数的benchmark
结果如下
BenchmarkTools.Trial: 47 samples with 1 evaluation.
Range (min … max): 102.527 ms … 130.312 ms ┊ GC (min … max): 0.00% … 0.00%
Time (median): 105.625 ms ┊ GC (median): 0.00%
Time (mean ± σ): 106.386 ms ± 4.531 ms ┊ GC (mean ± σ): 0.00% ± 0.00%
██
██▄▆▁▆▇▆▆▄▇▇▆▆▄▆▄▁▄▁▄▁▄▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▄ ▁
103 ms Histogram: frequency by time 130 ms <
Memory estimate: 0 bytes, allocs estimate: 0.
第二个函数的benchmark
结果如下
BenchmarkTools.Trial: 10000 samples with 996 evaluations.
Range (min … max): 24.322 ns … 38.767 ns ┊ GC (min … max): 0.00% … 0.00%
Time (median): 24.735 ns ┊ GC (median): 0.00%
Time (mean ± σ): 24.864 ns ± 0.898 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
█ ▅ ▂
▃▃▁█▂█▃█▃▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ ▂
24.3 ns Histogram: frequency by time 28.9 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
两个函数的性能差别非常大,但若将其改写成
function test1()
var1 = 100.
for i = 1:1e7
sin(var1)*cos(var1)
end
end
function test2()
var1 = 100.
cs = cos(var1)
ss = sin(var1)
for i = 1:1e7
ss*cs
end
end
则二者性能没有区别,请问这是为什么?