无论我是否增加线程数,执行时间都不会改变

The time of execution doesn't change whether I increase the number of threads or not

我正在按照 openMP 教程中的说明执行以下代码片段。但我看到的是执行时间不会随着 NUM_THREADS 而改变,事实上,执行时间一直在变化很多。我想知道我尝试测量时间的方式是否错误。我尝试使用 clock_gettime,但我看到了相同的结果。任何人都可以帮忙吗?不仅仅是使用openMP时间减少的问题,我很困惑为什么报告的时间差异很大。

#include "iostream"
#include "omp.h"
#include "stdio.h"
double getTimeNow();
static long num_steps = 10000000;
#define PAD 8
#define NUM_THREADS 1

int main ()
{ 

int i,nthreads;
double pi, sum[NUM_THREADS][PAD];
double t0,t1;

double step = 1.0/(double) num_steps;
t0 = omp_get_wtime();
#pragma omp_set_num_threads(NUM_THREADS);
#pragma omp parallel 
{
    int i, id,nthrds;
    double x;
    id = omp_get_thread_num();
    nthrds = omp_get_num_threads();
    if(id==0) nthreads = nthrds;
    for (i=id,sum[id][0]=0;i< num_steps; i=i+nthrds)
    {

     x = (i+0.5)*step;
         sum[id][0] += 4.0/(1.0+x*x);
    }
}
for(i=0, pi=0.0;i<nthreads;i++)pi += sum[i][0] * step;


t1 = omp_get_wtime();
printf("\n value obtained is %f\n",pi);
std::cout << "It took "
              << t1-t0
              << " seconds\n";

return 0;
}

你用了openmp_set_num_threads(),但它是一个函数,不是编译指令。你应该在没有 #pragma:

的情况下使用它
openmp_set_num_threads(NUM_THREADS);

另外,可以在编译指令中设置线程数,只是关键字不同:

#pragma omp parallel num_threads(4)

首选方法是不要在程序中硬编码线程数,而是使用环境变量 OMP_NUM_THREADS。例如,在 bash:

export OMP_NUM_THREADS=4

但是,最后一个示例不适合您的程序。