我有 2 个函数用于在 Julia 中以数字方式确定 pi。第二个函数(我认为是矢量化的)比第一个函数慢。
为什么矢量化较慢?何时进行矢量化和何时不进行矢量化是否有规则?
function determine_pi(n)
area = zeros(Float64, n);
sum = 0;
for i=1:n
if ((rand()^2+rand()^2) <=1)
sum = sum + 1;
end
area[i] = sum*1.0/i;
end
return area
end
和另一个功能
function determine_pi_vec(n)
res = cumsum(map(x -> x<=1?1:0, rand(n).^2+rand(n).^2))./[1:n]
return res
end
当运行 n=10^7 时,以下是执行时间(运行几次后)
n=10^7
@time returnArray = determine_pi(n)
#output elapsed time: 0.183211324 seconds (80000128 bytes allocated)
@time returnArray2 = determine_pi_vec(n);
#elapsed time: 2.436501454 seconds (880001336 bytes allocated, 30.71% gc time)
最佳答案
矢量化是好的,如果
一般来说,我个人认为最好从向量化代码开始,寻找任何速度问题,然后对任何麻烦的问题进行去向量化。
你的第二个代码慢不是因为它被向量化了,而是因为使用了匿名函数:不幸的是,在 Julia 0.3 中,这些通常要慢得多。
map
一般来说,性能不是很好,我相信是因为 Julia 无法推断函数的输出类型(从 map
函数的角度来看,它仍然是“匿名的”)。我写了一个不同的矢量化版本,它避免了匿名函数,并且可能更容易阅读:function determine_pi_vec2(n)
return cumsum((rand(n).^2 .+ rand(n).^2) .<= 1) ./ (1:n)
end
基准测试
function bench(n, f)
f(10)
srand(1000)
@time f(n)
srand(1000)
@time f(n)
srand(1000)
@time f(n)
end
bench(10^8, determine_pi)
gc()
bench(10^8, determine_pi_vec)
gc()
bench(10^8, determine_pi_vec2)
给我结果
elapsed time: 5.996090409 seconds (800000064 bytes allocated)
elapsed time: 6.028323688 seconds (800000064 bytes allocated)
elapsed time: 6.172004807 seconds (800000064 bytes allocated)
elapsed time: 14.09414031 seconds (8800005224 bytes allocated, 7.69% gc time)
elapsed time: 14.323797823 seconds (8800001272 bytes allocated, 8.61% gc time)
elapsed time: 14.048216404 seconds (8800001272 bytes allocated, 8.46% gc time)
elapsed time: 8.906563284 seconds (5612510776 bytes allocated, 3.21% gc time)
elapsed time: 8.939001114 seconds (5612506184 bytes allocated, 4.25% gc time)
elapsed time: 9.028656043 seconds (5612506184 bytes allocated, 4.23% gc time)
所以在某些情况下矢量化代码绝对可以和去矢量化一样好,即使我们不是在线性代数的情况下。
关于vectorization - Julia 何时支持向量化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648385/