我编写了一个简单的for循环,它为数组赋值。
#include <iostream>
#include <vector>
#include <cstdlib>
#include "omp.h"
using namespace std;
int nr_threads = 1;
long J = 10000000;
long K = 40;
int main(int argc, char* argv[])
{
nr_threads = atoi(argv[1]);
vector<double> H_U_d(J*K, 1);
double start_time = omp_get_wtime();
#pragma omp parallel for num_threads(nr_threads) schedule(static)
for(long j = 0; j < J*K; j++)
{
H_U_d[j] = 1;
}
cout << omp_get_wtime()-start_time << endl;
return 0;
}
我使用gcc编译它,g++ main.cpp -o test_speedup -fopenmp
并在12核机器上测试它。
我的系统是Ubuntu 14.04.3,cpu是Intel(R)Xeon(R)CPU E5-2620 0 @ 2.00GHz,内存为128GB。
如果没有应用优化,我们可以得到这样的结果:
➜~。/ test_speedup 1
2.95739
➜~。/ test_speedup 8
0.483756
加速大约是6。
但是如果我使用-O3来优化它,g++ main.cpp -o test_speedup -fopenmp -O3
结果是
➜~。/ test_speedup 1
0.379158
➜~。/ test_speedup 8
0.265842
加速很差。
gcc如何优化循环?有没有解决办法可以避免这种情况?
答案 0 :(得分:1)
您的矢量H_U_d
无法放入处理器的缓存中。因此,您的性能可能受主内存带宽的限制。在主内存带宽被工作线程饱和后,更多线程将只需等待内存。
如果您在多插槽计算机上运行,您可能还会遇到一些numa效果。更具体的答案需要有关我们系统(处理器,内存,操作系统)的更多信息。