我运行一个非常简单的程序在C++中使用OpenMP和测量所经过的时间...代码在去读取,OpenMP的C++ GCC基本套路
#include <iostream>
#include <math.h>
#include "timer.h"
#include <omp.h>
int main()
{
double start,finish;
int i;
int n=8000;
double a[n];
double b[n];
double c[n];
GET_TIME(start);
#pragma omp parallel private(i,a) shared(b,c,n)
{
#pragma omp for
for (i=0; i<n-1; i++)
b[i] += (a[i] + a[i+1])/2;
#pragma omp for
for (i=0; i<n-1; i++)
c[i] += (a[i] + a[i+1])/2;
}
GET_TIME(finish);
std::cout<< "Elapsed time is" <<(finish-start)<<"seconds";
return 0;
}
代码我用下面的编译bash脚本(观察到线程在环境中定义变量OMP_NUM_THREADS = $ N):
#!/bin/bash
clear
g++ -O3 -o test test.cpp -fopenmp
for n in $(seq 1 8); do
export OMP_NUM_THREADS=$n
./test
echo threads=$n
done
其结果是,随着增加线程的数量降低性能的一般趋势被观察为如下:(当然数字可以改变)...
Elapsed time is0.000161886secondsthreads=1
Elapsed time is0.00019002secondsthreads=2
Elapsed time is0.00226498secondsthreads=3
Elapsed time is0.000210047secondsthreads=4
Elapsed time is0.000212908secondsthreads=5
Elapsed time is0.00920105secondsthreads=6
Elapsed time is0.00937104secondsthreads=7
Elapsed time is0.000834942secondsthreads=8
有关提高性能(而不是减少它)的任何建议? 非常感谢!
如果我正确读取了您的数字,从7个线程到8个线程的执行速度增加了10倍以上 - 性能显着提高。我建议你用更大和更长的循环重新计时,并在尝试得出任何结论之前平均进行3-5次运行。 –
谢谢马克..也许我最经常得到的是:8.39233e-05secondsthreads = 1经过的时间是0.000119925secondsthreads = 2经过的时间是0.000138044secondsthreads = 3经过的时间是0.000128044secondsthreads = 4经过的时间是0.00secondsthreads = 5经过的时间is0.000133991secondsthreads = 6已用时间为0.00356102secondsthreads = 7已用时间为0.00615597secondsthreads = 8 ....当我增加线程时总会变得最差...我知道Loop不够大,但是有没有办法用SIMD fe等其他技术改进它?谢谢!。 – uom0