OpenMP环境下PI计算

xg910813 贡献于2012-10-30

作者 sunzq  创建于2012-10-30 03:22:00   修改者lenovo  修改于2012-10-30 08:09:00字数2036

文档摘要:掌握OpenMP基本编程方法,实现四个OpenMP计算PI的程序,在此基础上,采用不同的分配策略,并计算出加速比。
关键词:

实验二 OpenMP环境下PI计算; 姓名 学号 专业班级 成绩_________ 实验日期________ 实验地点 指导教师(签名) 一.实验目的 掌握OpenMP基本编程方法,实现四个OpenMP计算PI的程序,在此基础上,采用不同的分配策略,并计算出加速比。 二.实验工具与设备 三.实验内容 1.了解在VS系统中OpenMP的配置 2.程序设计 Pi的计算 (1) 串行程序 static long num_steps = 100000; double x, pi, sum = 0.0, step = 1.0/(double) num_steps; for (long i = 1; i <= num_steps; i++){ x = (i + 0.5)*step; sum += 4.0/(1.0 + x*x); } (2) 并行程序1(并行区域) #define NUM_THREADS 2 static long num_steps = 100000; double x, pi = 0.0, sum[NUM_THREADS], step = 1.0/(double)num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int id = omp_get_thread_num(); sum[id] = 0.0; for (long i = id; i < num_steps; i += NUM_THREADS) { x = (i + 0.5)*step; sum[id] += 4.0/(1.0 + x*x); // 根据ID号分配任务 } } for(int i = 0; i < NUM_THREADS; i++) pi += sum[i] * step; printf("Pi = %f\n", pi); (3) 并行程序2(循环并行化) #define NUM_THREADS 2 static long num_steps = 100000; double x, pi = 0.0, sum[NUM_THREADS], step = 1.0/(double)num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel { int id = omp_get_thread_num(); sum[id] = 0.0; #pragma omp for for (long i = 0; i < num_steps; i++) { x = (i + 0.5)*step; sum[id] += 4.0/(1.0 + x*x); // 存储每次的结果 } } for(int i = 0; i < NUM_THREADS; i++) pi += sum[i] * step; printf("Pi = %f\n", pi); (4) 并行程序3(私有化和临界区) #define NUM_THREADS 2 static long num_steps = 100000; double x, pi = 0.0, sum, step = 1.0/(double)num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel private(x, sum) { int id = omp_get_thread_num(); sum = 0.0; for (long i = id; i < num_steps; i += NUM_THREADS) { x = (i + 0.5)*step; sum += 4.0/(1.0 + x*x); } #pragma omp critical pi += sum*step; } printf("Pi = %f\n", pi); (5) 并行程序4(归约操作) #define NUM_THREADS 2 static long num_steps = 100000; double x, pi = 0.0, sum = 0.0, step = 1.0/(double)num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel for reduction(+:sum) private(x) for (long i = 0; i < num_steps; i++) { x = (i + 0.5)*step; sum += 4.0/(1.0 + x*x); } pi += sum*step; printf("Pi = %f\n", pi); 用以下程序段测试,并给出输出结果。 long long freq, countBegin, countEnd; QueryPerformanceFrequency((LARGE_INTEGER *)&freq); QueryPerformanceCounter((LARGE_INTEGER *)&countBegin); …… QueryPerformanceCounter((LARGE_INTEGER *)&countEnd); printf("CPU频率:%lld, 计数:%lld, 耗时:%f秒\n", freq, countEnd - countBegin, (countEnd - countBegin) / (double)freq); 四.思考题 1.怎样用OpenMP实现多线程编程时,多线程的起始点在哪里? 2.写出以上4段程序中的变量的所有作用域。

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档