Openmp并行计算pi π
程序员文章站
2022-07-12 20:02:55
...
Openmp并行计算pi π
#include"stdio.h"
#include"omp.h"
#include<time.h>
#include<Windows.h>
#include<ctime>
#include<sys/timeb.h>
#define NUM_THREADS 8
static long n = 10000000;
double h;
int main()
{
int i;
double pi, sum[NUM_THREADS];
for (i = 0;i < NUM_THREADS;i++) {
sum[i] = 0.0;
}
h = 1.0 / (double)n;
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
double x;
int tid;
#pragma omp for
for (i = 0;i < n;i++)
{
tid = omp_get_thread_num();
x = (i + 0.5) * h;
sum[tid] += 4.0 / (1.0 + x * x);
}
}
for (i = 0, pi = 0.0;i < NUM_THREADS;i++) {
pi += sum[i] * h;
}
printf("Approximation of pi%15.13f\n", pi);
}
编译运行结果如下:
使用的编译器是g++;工具借助vscode;大家也可以使用visual studio配置一下openmp就行。
可以添加时间戳对比并行与非并行效率
#include<iostream>
using namespace std;
#include<cstdio>
#include"omp.h"
#include"time.h"
#include<ctime>
#include<windows.h>
#include<sys/timeb.h>
#define NUM_THREADS 8
static long n = 10000000;
double h;
LARGE_INTEGER t1, t2, tc;
int main()
{
int i;
double x,pi,sum = 0.0;
h=1.0/(double)n;
omp_set_num_threads(NUM_THREADS);
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
#pragma omp parallel for reduction(+:sum) private(x)
for (i = 0; i < n;i++)
{
x = (i + 0.5) * h;
sum += 4.0 / (1.0 + x * x);
}
QueryPerformanceCounter(&t2);
long time = (double)(t2.QuadPart - t1.QuadPart) * 1000000 / (double)tc.QuadPart;
cout << "time = " << time / 1000.0 << "ms" << endl;
pi = sum * h;
printf("Appromxation of pi:%15.13f\n", pi);
return 0;
}
编译运行结果如下:
下一篇: webpack的配置文件