【发布时间】:2013-12-08 16:19:41
【问题描述】:
我正在学习 OpenMP,但遇到了一些问题: 并行程序比串行程序慢,我很困惑(1 线程 vs 2 线程) 我的代码:
#include <iostream>
#include <omp.h>
using namespace std;
int main()
{
int threadsNumber=1;
int S=0;
cout << "Enter number of threads:\n";
cin >> threadsNumber;
double start, end, calculationTime;
omp_set_num_threads(threadsNumber);
start = omp_get_wtime();
#pragma omp parallel for reduction(+: S)
for(int i=1;i<1000;i++) {
S+= 10;
}
#pragma omp end parallel
end = omp_get_wtime();
calculationTime = end - start;
cout << "Время выполнения: " << calculationTime << "\n";
cout<<"S = "<< S <<"\n";
return 0;
}
结果: 1 个线程:2.59876e-05 2 个线程:0.000102043
我的错误在哪里? 谢谢!
【问题讨论】:
-
我不是 100% 确定,但最后的减少可能会消耗更多的时间,而不是使用 2 个线程节省的时间。也许更复杂的计算会给你更好的结果
-
尝试
1000000000而不是1000。它应该为 1 个线程返回 2 秒,为 2 个线程返回 1 秒。如果启用了编译器优化,则使用volatile变量来防止优化循环。 -
你是对的!谢谢!
-
要补充一点:没有“#pragma omp end parallel”。由于您正在编写 C++ 代码,因此并行区域的结束由结构块的结束自动确定。
标签: c++ multithreading openmp