简体   繁体   English

OpenMP循环并行化

[英]OpenMP loop parallelize

I'm learning OpenMP and have some problems: Parallel program slower than serial, i'm confusing (1 thread vs 2 threads) My code: 我正在学习OpenMP并遇到一些问题:并行程序比串行程序慢,我很困惑(1个线程对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;
}

Results: 1 thread: 2.59876e-05 2 threads: 0.000102043 结果:1个主题: 2.59876e-05 2个主题: 0.000102043

Where my mistake? 我的错误在哪里? Thank you! 谢谢!

As JF Sebastian pointed out in a comment, you don't get much benefit from parallelization because your loop with 1000 iterations is rather quick. 正如JF Sebastian在评论中指出的那样,并没有从并行化中获得太多好处,因为1000次迭代的循环相当快。 That means the overhead it takes to create a 2nd thread is larger than what you save due to parallelization. 这意味着创建第二个线程所需的开销大于由于并行化而节省的开销。 When you increase the number of loop iterations and thus give the threads more to do, the benefit of multi-threading becomes more apparent. 当你增加循环迭代的次数并因此给线程做更多的事情时,多线程的好处变得更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM