2017-02-21 59 views
0

每當我運行此代碼時,它都會顯示並行部分所執行的不同運行時間。根據我的核心,我嘗試了不斷的線程數,但仍然是徒勞無功。該計劃是計算pi的價值。編爲gcc -fopenmp改變OpenMP並行區域的運行時間

#include <stdio.h> 
#include <omp.h> 

static long num_steps = 100000; double step; 
//double omp_get_wtime(void); 

int main(){ 
     int i; 
     double x,pi,max_threads,start,time; 
     double sum=0.0; 
     step = 1.0/(double) num_steps; 
    //omp_set_num_threads(4);  
     omp_get_max_threads(); 
     start=omp_get_wtime(); 

    #pragma omp parallel 
    { 

    #pragma omp for reduction(+:sum) schedule(static) private(x) //reduction to get local copy 
      for (i=0;i<num_steps;i++){ 
      x=(i+0.5)*step; 
      sum += 4.0/(1.0+x*x); 
      } 
    //max_threads=omp_get_max_threads(); 
    } 
time=omp_get_wtime()-start; 
pi=step*sum; 
printf("pi=(%f)\t run_time(%f)\n",pi,time);//,max_threads); 
return 0; 
} 
+2

歡迎來到Stack Overflow!你的問題的題目是非常通用的,絕不反映實際問題。請花點時間在幫助部分閱讀[我如何提出一個好問題?](http://stackoverflow.com/help/how-to-ask)。 –

+0

對於一致的運行時間,一個典型的要求是固定線程並避免來自其他任務的競爭。如果你正在做一個簡單的總和減少和防止simd優化,這個任務是沒有意義的。 – tim18

回答

0

該代碼只運行幾毫秒(在我的系統2-6毫秒),時間被佔據主導地位,例如,爲線程創建。串行版本運行< 1 ms。由於這樣短的執行時間取決於系統的當前狀態,所以這是很常見的,例如,有一些'熱身需要'。

在這種情況下,只需增加num_steps即可獲得有意義的穩定結果。例如。與num_steps = 1000000000,在我的系統上執行10次都在4.332秒和4.399秒之間。

通常,如果您進行性能測量,則應使用-O3標誌進行編譯。