簡體   English   中英

OpenMP循環並行化

[英]OpenMP loop parallelize

我正在學習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;
}

結果:1個主題: 2.59876e-05 2個主題: 0.000102043

我的錯誤在哪里? 謝謝!

正如JF Sebastian在評論中指出的那樣,並沒有從並行化中獲得太多好處,因為1000次迭代的循環相當快。 這意味着創建第二個線程所需的開銷大於由於並行化而節省的開銷。 當你增加循環迭代的次數並因此給線程做更多的事情時,多線程的好處變得更加明顯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM