使用C语言编写程序需要获得当前精确时间(UNIX到现在的时间),或者为执行计时,可以使用gettimeofday()函数。它的[1]

 

  #include <sys/time.h>

 

  int gettimeofday(struct timeval *tv, struct timezone *tz);

 

  其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果(若不使用则传入NULL即可)。

 

  结构体timeval的定义为:

 

  struct timeval {

 

  long tv_sec; // 秒数

 

  long tv_usec; // 微秒数

 

  }

 

  它获得的时间精确到微秒(1e-6 s)量级。在一段代码前后分别使用gettimeofday可以计算代码执行时间:

 

  struct timeval tv_begin, tv_end;

 

  gettimeofday(&tv_begin, NULL);

 

  foo();

 

  gettimeofday(&tv_end, NULL);

 

  执行时间(微秒) = 1000000 * (tv_end.tv_sec - tv_begin.tv_sec) + tv_end.tv_usec - tv_begin.tv_usec;

 

 
posted on 2012-11-15 16:25  Sparkjin  阅读(470)  评论(0编辑  收藏  举报