使用 OpenMP 并行C++代码不会即兴发挥性能

parallelizing C++ code with OpenMP doesn't improove performance

本文关键字:性能 OpenMP 并行 C++ 代码 使用      更新时间:2023-10-16

我写了一个c++代码来计算一些数字。我试图使用OpenMP库来并行化它。它有3个嵌套的for循环,并行化的是最外层的。我用g++编译器在Linux上工作。代码可以工作,但问题是并行化并没有提高性能。在我的双核笔记本电脑(intel i5处理器关闭多线程)上,用2个线程启动它比只用一个线程执行它要花更多的时间。

下面是代码(使用:g++ source.cpp -fopenmp启动):
#include <time.h>
clock_t tStart = clock();
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <omp.h>
using namespace std;
int nThreads= 2; // switch to change the number of threads.
int main () {
    int i, j, k, nz= 10;
    double T= 1000, deltaT= 0.005, g= 9.80665, h=10, dz= h/nz, t, z, V, A;
    int nT= T/deltaT;
    #pragma omp parallel for private (j, k, t, z, V, A) num_threads(nThreads)
    for (i=0; i<=nT; i++) {
        t= i*deltaT;
        for (j=0; j<=nz; ++j) {
            z= dz*j;
            for (k=0; k<=1000; k++) {
                V= t*z*g*k;
                A= z*g*k;
            }
        }
    }
    cout << "Time taken: " << setprecision(5) <<  (double)(clock() - tStart)/CLOCKS_PER_SEC << endl;
    return 0;
}

好的,很好。我在测量cpu时间,结果是一致的。Time()函数给出了我需要知道的数字。问题解决了。谢谢所有人。