如何使用struct timeval来获取执行时间?

在阅读了这篇关于经过时间的文章后,我编写了一个简单的代码来计算循环的执行时间:

#include  #include  int main (int argc, char** argv) { struct timeval, tvalBefore, tvalAfter; gettimeofday (&tvalBefore, NULL); int i =0; while ( i < 1000) { i ++; } gettimeofday (&tvalAfter, NULL); printf("Time in microseconds: %0.3f microseconds\n", (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) ) return 0; } 

clang编译器给我以下错误:

 print_time.c:7:16: error: expected identifier or '(' struct timeval, *tvalBefore, *tvalAfter; ^ print_time.c:13:17: error: use of undeclared identifier 'tvalBefore' gettimeofday (&tvalBefore, NULL); ^ print_time.c:19:17: error: use of undeclared identifier 'tvalAfter' gettimeofday (&tvalAfter, NULL); ^ print_time.c:22:12: error: use of undeclared identifier 'tvalAfter' (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) ^ print_time.c:22:31: error: use of undeclared identifier 'tvalBefore' (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) ^ 5 errors generated. 

我无法弄清楚我的代码有什么问题,任何想法?

您的代码中有两个输入错误:

  struct timeval, 

应该

  struct timeval 

printf()括号后你需要一个分号。

此外,根据编译器的不同,这么简单的循环可能只是优化出来,无论你做什么,都会给你0微秒的时间。

最后,时间计算是错误的。 您只考虑秒数,忽略微秒。 你需要得到秒之间的差异,乘以一百万,然后添加“之后” tv_usec并减去“之前” tv_usec 。 通过向浮点数转换整数秒来获得任何结果。

我建议查看struct timeval的手册页。

这是代码:

 #include  #include  int main (int argc, char** argv) { struct timeval tvalBefore, tvalAfter; // removed comma gettimeofday (&tvalBefore, NULL); int i =0; while ( i < 10000) { i ++; } gettimeofday (&tvalAfter, NULL); // Changed format to long int (%ld), changed time calculation printf("Time in microseconds: %ld microseconds\n", ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L +tvalAfter.tv_usec) - tvalBefore.tv_usec ); // Added semicolon return 0; } 

更改:

 struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to delcare a variable with no name. */ 

至:

 struct timeval tvalBefore, tvalAfter; 

如果每行有一个声明,则不太可能(IMO)犯这个错误:

 struct timeval tvalBefore; struct timeval tvalAfter; 

在单行上声明指向类型的指针时,它会更容易出错:

 struct timeval* tvalBefore, tvalAfter; 

tvalBefore是一个struct timeval*但是tvalAfter是一个struct timeval