【发布时间】:2021-04-10 03:00:41
【问题描述】:
我对并发和并行编程的一般概念并不陌生。我正在尝试在 C 中使用 Monte Carlo method 计算 Pi。这是我的源代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(void)
{
long points;
long m = 0;
double coordinates[2];
double distance;
printf("Enter the number of points: ");
scanf("%ld", &points);
srand((unsigned long) time(NULL));
for(long i = 0; i < points; i++)
{
coordinates[0] = ((double) rand() / (RAND_MAX));
coordinates[1] = ((double) rand() / (RAND_MAX));
distance = sqrt(pow(coordinates[0], 2) + pow(coordinates[1], 2));
if(distance <= 1)
m++;
}
printf("Pi is roughly %lf\n", (double) 4*m / (double) points);
}
当我尝试使用 openmp api 使该程序并行运行时,它的运行速度几乎慢了 4 倍。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <omp.h>
#include <sys/sysinfo.h>
int main(void)
{
long total_points; // Total number of random points which is given by the user
volatile long total_m = 0; // Total number of random points which are inside of the circle
int threads = get_nprocs(); // This is needed so each thred knows how amny random point it should generate
printf("Enter the number of points: ");
scanf("%ld", &total_points);
omp_set_num_threads(threads);
#pragma omp parallel
{
double coordinates[2]; // Contains the x and y of each random point
long m = 0; // Number of points that are in the circle for any particular thread
long points = total_points / threads; // Number of random points that each thread should generate
double distance; // Distance of the random point from the center of the circle, if greater than 1 then the point is outside of the circle
srand((unsigned long) time(NULL));
for(long i = 0; i < points; i++)
{
coordinates[0] = ((double) rand() / (RAND_MAX)); // Random x
coordinates[1] = ((double) rand() / (RAND_MAX)); // Random y
distance = sqrt(pow(coordinates[0], 2) + pow(coordinates[1], 2)); // Calculate the distance
if(distance <= 1)
m++;
}
#pragma omp critical
{
total_m += m;
}
}
printf("Pi is roughly %lf\n", (double) 4*total_m / (double) total_points);
}
我尝试查找原因,但对不同的算法有不同的答案。
【问题讨论】:
标签: c++ c multithreading parallel-processing openmp