OPENMP计算PI的值

目录

实验设备:

实验环境:

没有加并行的程序:

源代码:

实验结果:

(n=100000)

(n=10000000)

(n=100000000)

 加上OPENMP语句和critical语句的程序

源代码:

实验结果:

(n=100000)

(n=10000000)

(n=100000000)

加上OPENMP语句和reduction语句的程序

源代码:

实验结果:

(n=100000)

(n=10000000)

(n=100000000)

 加上OPENMP语句和private子句和critical的程序

源代码:

实验结果:

(n=100000)

(n=10000000)

(n=100000000)

 实验记录表:


实验理论:

代码思路就是:设f(x)=4/(1+x*x),求f(x)在0-1的积分,分四个线程,分别就行求和再相加。

任务线程的分配模式:

 

实验设备:

i5 4核4线程处理器  win10 64位,vs 2022

实验环境:

其他软件关闭,CPU利用率在10%,GPU的利用率在4%左右。

没有加并行的程序:

源代码:

#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include <iostream>
using namespace std;


double  f(double m)  //构造函数f(x)=4/(1+x*x)
{
	
	double result;
	result = 4 / (1 + m * m);
	return result;
}
void Trap(double a, double b, int n, double* global_result_p)
{

	double h;
	int i;
	h = (b - a) / n;
	double x_i;
	*global_result_p = (f(a) + f(b)) / 2;
	cout << *global_result_p << endl;
	for ( i = 0; i <=n-1; i++)
	{
		x_i = a + i * h;
		*global_result_p += f(x_i);

	}
	*global_result_p = h * ( * global_result_p);
}
int main(int argc,char* argv[])
{
	double global_result = 0.0;
	double a = 0, b = 1;
	int n = 100000;
	
	double start_time;
	double end_time;
	start_time = clock();
	
	Trap(a, b, n, &global_result);


	end_time = clock();

	double runtime = (double)(end_time - start_time) / CLOCKS_PER_SEC;
	cout << "PI的值为" << global_result << endl;
	cout << "Running time is  " << runtime << "s" << endl;
	return 0;

}

实验结果:

(n=100000)

(n=10000000)

(n=100000000)

 

 加上OPENMP语句和critical语句的程序

源代码:

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include <iostream>
using namespac
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值