C OMP omp_get_wtime()返回时间0.00

我使用了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); } 

确保在文件头中包含omp.h库。

 #include  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] 

时间会正确显示。

尝试使用“%g”进行打印,使其成为科学记数法。

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

  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 

这是因为将double转换为float时的精度损失

对于“%f”的双重输入 ,尝试使用格式说明符“%ld”打印时间。

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

程序执行需要的时间以毫秒为单位,或者可能小于该值。

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

您的例程可能太快,无法解析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 

您可能还想在并行块内部压缩printf's ,因为这可能是导致速度减慢的严重原因。

我有同样的问题,而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); 

当@mcleod_ideafix写下关于printf的压制时,他是对的。 你绝对应该从循环中删除对printf函数的调用,因为它可能会大大扭曲结果。 请记住,对printf的调用将在某个阶段涉及到内核模式的转换,这本身就CPU周期而言是昂贵的操作。