2026-01-21 18:02:30 +08:00

40 lines
973 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <omp.h>
#include <sys/time.h>
long long num_steps = 1000000000;
double step;
int main(int argc, char* argv[])
{
struct timeval TimeStampStart, TimeStampStop;
double ExeTime;
double x, pi, sum=0.0;
int i;
step = 1./(double)num_steps;
gettimeofday(&TimeStampStart, NULL);
// 并行计算PI使用OpenMP的reduction合并部分和
#pragma omp parallel private(x) reduction(+:sum)
{
#pragma omp for
for (i=0; i<num_steps; i++)
{
x = (i + .5)*step;
sum = sum + 4.0/(1.+ x*x);
}
}
pi = sum*step;
gettimeofday(&TimeStampStop, NULL);
ExeTime = (double)(TimeStampStop.tv_sec - TimeStampStart.tv_sec) +
(double)(TimeStampStop.tv_usec - TimeStampStart.tv_usec) * 1e-6;
printf("The value of PI is %15.12f\n",pi);
printf("The time to calculate PI was %f seconds\n", (ExeTime));
return 0;
}