我需要计算运行某个函数所花费的时间并遇到以下代码(来源:http://snippets.dzone.com/posts/show/4254)声称“......以微秒为单位记录并输出一段代码的执行时间"
/* 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);
但我对这段代码的个人经验表明,输出“时间”的单位是秒而不是微秒。我需要一些意见来判断我是对还是错(我需要一劳永逸地澄清这一点)。
最佳答案
你是对的。
结构体的tv_sec
成员存储秒,tv_usec
成员(微秒)除以10^6转换为秒。
关于c - C 中时间结构所需的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6536407/