【发布时间】:2018-04-20 19:49:49
【问题描述】:
Without using Open MP Directives - serial execution - check screenshot here
Using OpenMp Directives - parallel execution - check screenshot here
#include "stdafx.h"
#include <omp.h>
#include <iostream>
#include <time.h>
using namespace std;
static long num_steps = 100000;
double step;
double pi;
int main()
{
clock_t tStart = clock();
int i;
double x, sum = 0.0;
step = 1.0 / (double)num_steps;
#pragma omp parallel for shared(sum)
for (i = 0; i < num_steps; i++)
{
x = (i + 0.5)*step;
#pragma omp critical
{
sum += 4.0 / (1.0 + x * x);
}
}
pi = step * sum;
cout << pi <<"\n";
printf("Time taken: %.5fs\n", (double)(clock() - tStart) / CLOCKS_PER_SEC);
getchar();
return 0;
}
我试了多次,为什么串行执行总是更快?
串行执行时间:0.0200s 并行执行时间:0.02500s
为什么这里的串行执行速度更快?我是否以正确的方式计算执行时间?
【问题讨论】:
-
请记住创建线程需要时间,而您的算法不会花费太多时间。
-
哦,是这样吗,谢谢!
-
很多事情都会导致并行执行比非并行慢。例如:启动线程的开销超过了每个线程完成的工作。同步的成本超过了并行运行的好处。错误共享(由于错误/无知的实现)会破坏线程版本的性能。还有很多很多。线程是困难,不是灵丹妙药。
-
注意点!感谢您的澄清。
-
回答您的问题:不,您没有正确计时执行时间。请参阅stackoverflow.com/questions/13351396/… 和其他几个,了解为什么不使用
clock来为并行程序计时。
标签: c++ parallel-processing openmp