我有两个函数用于在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
Run Code Online (Sandbox Code Playgroud)
和另一个功能
function determine_pi_vec(n)
res = cumsum(map(x -> x<=1?1:0, rand(n).^2+rand(n).^2))./[1:n]
return res
end
Run Code Online (Sandbox Code Playgroud)
当运行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)
Run Code Online (Sandbox Code Playgroud)