2017-08-12 104 views
1

这里是一个玩具的例子,我把使用CPU加速执行的parfoor函数放在一起。即使在审查了Parallel文档之后,我仍然很困惑如何将它升级到我的GPU上运行(Nvidia 980ti)。使用并行工具箱的GPU上的简单蒙特卡洛

希望有关如何更新此代码在GPU上运行的任何指针。

干杯。

% toy example--monte carlo estimation of pi using for loops 
tic; 
N = 1000000000; 
hitcounter = 0; 
for i = 1:N 
    x = rand; 
    y = rand; 
    if (y < sqrt(1-x*x)) 
     hitcounter = hitcounter + 1; 
    end 
end 
disp(hitcounter/N*4) 
toc; 

% toy example--monte carlo estimation of pi using parfor loops 
tic; 
N = 1000000000; 
hitcounter = 0; 
parfor i = 1:N 
    x = rand; 
    y = rand; 
    if (y < sqrt(1-x*x)) 
     hitcounter = hitcounter + 1; 
    end 
end 
disp(hitcounter/N*4) 
toc; 

回答

1

你需要做的主要事情就是引导你的代码 - 这总是一个好主意,尤其是在GPU上。然后,您只需使用尾部参数rand直接在GPU上构建xy

N = 1000000; 
x = rand(1, N, 'gpuArray'); 
y = rand(1, N, 'gpuArray'); 
pi_est = sum(y < sqrt(1 - x.*x))/N * 4; 

注意我缩回N以使其适合GPU。如果你想运行更高的值N - 我会建议添加一个外部循环,并基本上执行适合GPU有限内存的“块”计算。