Openmp并行计算pi π
Posted 各可
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Openmp并行计算pi π相关的知识,希望对你有一定的参考价值。
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;
}
编译运行结果如下:
以上是关于Openmp并行计算pi π的主要内容,如果未能解决你的问题,请参考以下文章
使用非线程安全随机数生成器在 C 中为 pi monte carlo 更正 OpenMP 编译指示