C OMP omp_get_wtime()返回时间0.00

时间:2013-05-27 17:18:42

标签: c multithreading openmp

我使用过omp_get_wtime()但是当我想要打印时间总是得到0.00时,问题出在哪里?

#define SIZE 500
#define nthreads 10

(...)

void sumTab(int mX[][SIZE], int mY[][SIZE], int mZ[][SIZE]) {
int i,k;
double start = omp_get_wtime();
#pragma omp parallel for schedule(dynamic,3) private(i) num_threads(nthreads)
for(i=0 ; i<SIZE ; i++)
{

   for(k=0 ; k<SIZE ; k++)  
   {

     mZ[i][k]=mX[i][k]+mY[i][k];
     printf("Thread no %d \t  [%d] [%d] result: %d\n", omp_get_thread_num(),i,k, mZ[i][k]); 
     }
}

printf("Time: \t %f \n", omp_get_wtime()-start); 
}

7 个答案:

答案 0 :(得分:14)

确保在文件的标题中包含omp.h库。

#include <omp.h>

double start_time = omp_get_wtime();
#pragma omp parallel [...]
// code
double time = omp_get_wtime() - start_time;

此库将在编译中删除此警告:

warning: implicit declaration of function ‘omp_get_wtime’ [-Wimplicit-function-declaration]

时间会正确显示。

答案 1 :(得分:2)

尝试使用“%g”打印,将其留作科学记数法。

答案 2 :(得分:0)

声明程序结束的时间,然后取出开始时间和结束时间之间的差值,输出差值。应该解决它,因为几个月前我做了类似的事情

 THis is what  your code should look like:
 double  dif;
 double start = omp_get_wtime( ); //start the timer
 //beginning of computation
 ..
 ...
//end of computation
    double end = omp_get_wtime();// end the timer
   dif = end - start // stores the difference in dif
  printf("the time of dif is %f", dif);
 //this should point you in the way

答案 3 :(得分:0)

这是因为在将double转换为float时出现了精度损失

尝试使用格式说明符“%ld” 打印时间,以 double 插入“%f”。

printf("the time of dif is %lf", dif);

程序执行所花费的时间(以毫秒为单位),甚至可以少于该时间。

答案 4 :(得分:-1)

声明程序结束的时间,然后取出开始时间和结束时间之间的差值,输出差值。应该解决它,因为几个月前我做了类似的事情

答案 5 :(得分:-1)

我有同样的问题,而setprecision在c ++中做了诀窍, 你可以在c中使用以下代码。为了看到差异,您必须高精度地打印结果。

double exec_time;
double start = omp_get_wtime();
//beginning of computation
...
//end of computation
double end = omp_get_wtime();
exec_time = end - start;
printf("the time difference is %15.15f", exec_time);

答案 6 :(得分:-1)

你的例行程序可能太快而无法解决omp_get_wtime。如果您只想测量时间并且不关心mZ的最终内容,您可以多次重复测试并将最终数字除以重复次数:

#define REPS 1024
...
...

double acumtime = 0.0;
for (rep = 0; rep < REPS; rep++)
{
  double start = omp_get_wtime();
  #pragma omp parallel for schedule(dynamic,3) private(i) num_threads(nthreads)
  for(i=0 ; i<SIZE ; i++)
  {
    for(k=0 ; k<SIZE ; k++)  
    {
      mZ[i][k]=mX[i][k]+mY[i][k];
      printf("Thread no %d \t  [%d] [%d] result: %d\n", omp_get_thread_num(),i,k, mZ[i][k]); 
    }
  }
  acumtime += omp_get_wtime()-start; 
}
printf ("Elapsed time is: %f\n", acumtime/REPS);

您可能还想在并行块中隐藏printf's,因为这可能是导致速度放缓的严重原因。