簡體   English   中英

空OpenMP的循環耗時5毫秒

[英]Empty OpenMP for loop taking 5 ms

我在test.cpp中有以下C ++代碼:

int myfun(){
double time1, time2;
time1 = omp_get_wtime();

#pragma omp parallel for 
for(int group_id = 0; group_id < 1; ++group_id){ }

time2 = omp_get_wtime();
printf("computation took %.3f ms\n", (time2-time1)*1000);
return 0;
}

我將其編譯為共享庫

g++ -c -fPIC -fopenmp -std=c++11 -Wall -march=native -O3 -o test.o test.cpp

其次是

g++ -shared -fopenmp -o mylib.so test.o

當我運行函數myfun()時(如果很重要,我會從python程序中調用它),得到以下輸出:

computation took 5.992 ms

如果我注釋掉#pragma指令,我當然會得到

computation took 0.000 ms

現在,我了解到使用openmp會有一些開銷,但這似乎是不合理的。 我在這里想念什么?

這很正常。 多線程編程會帶來額外的開銷,例如創建線程,同步等。但是正確應用多線程編程會取得成功。 選擇順序或多線程實現取決於其有效性。 在我的示例中,線程是在第一個調用中創建的,然后被使用。 但這取決於實現:

int main()
{
    myfun();
    myfun();
    myfun();
    myfun();
    return 0;
}

輸出:

computation took 2.510 ms
computation took 0.082 ms
computation took 0.046 ms
computation took 0.043 ms

暫無
暫無

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

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