我需要计算运行某个函数所需的时间,并遇到以下代码(来源:http://snippets.dzone.com/posts/show/4254 ),声明"...record &以微秒为单位输出一段代码的执行时间“
/* Put this line at the top of the file: */
#include <sys/time.h>
/* Put this right before the code you want to time: */
struct timeval timer_start, timer_end;
gettimeofday(&timer_start, NULL);
/* Put this right after the code you want to time: */
gettimeofday(&timer_end, NULL);
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec) / 1000000.0;
printf("Time spent: %.6f\n", timer_spent);但我个人对这段代码的经验表明,输出“时间”是以秒为单位的,而不是微秒。我需要一些关于我是对还是错的意见(我需要一劳永逸地澄清这一点)。
发布于 2011-06-30 22:34:23
你是正确的。
该结构的tv_sec成员存储秒,tv_usec成员(微秒)通过除以10^6转换为秒。
发布于 2011-06-30 22:35:22
它提供了以秒为单位的时间差和微秒(具有以下术语:(timer_end.tv_usec - timer_start.tv_usec))。所以你应该没问题:)
发布于 2011-06-30 22:34:35
如下所示修改:
double timer_spent = (timer_end.tv_sec - timer_start.tv_sec)*1e6 + (timer_end.tv_usec - timer_start.tv_usec);https://stackoverflow.com/questions/6536407
复制相似问题