我想在OpenMP中使用線程實現以下代碼的並行版本,有沒有更好的方法來做到這一點?實現並行算法來計算pi
/* Program to compute Pi using Monte Carlo methods */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define SEED 35791246
int main(int argc, char* argv)
{
int niter=0;
double x,y;
int i,count=0; /* # of points in the 1st quadrant of unit circle */
double z;
double pi;
clock_t end_time, start_time;
printf("Enter the number of iterations used to estimate pi: ");
scanf("%d",&niter);
start_time = clock();
/* initialize random numbers */
srand(SEED);
count=0;
#pragma omp parallel for
for (i=0; i<niter; i++) {
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
z = x*x+y*y;
if (z<=1) count++;
}
#pragma omp task
pi=(double)count/niter*4;
#pragma omp barrier
end_time = clock();
printf("# of trials= %d , estimate of pi is %g, time= %f \n",niter,pi, difftime(end_time, start_time));
return 0;
}
這一切對我來說都是有意義的。現在我仍然在學習如何使用OpenMP進行並行計算。根據Brooks的建議,我確實在私有(i,x,y,z)減少(+:count)時指定了#pragma omp parallel循環的頂部並再次運行程序。與串行算法相比,它仍然花費了更長的時間來進行計算。這使我想到rand函數的gabe引發的問題,它不是線程友好的。如何分配新的隨機種子在每個線程或在我的代碼中使用不同的隨機數發生器來提高算法的性能? – kayn 2010-03-02 11:04:23