c - C 中时间结构所需的帮助

标签 c struct

我需要计算运行某个函数所花费的时间并遇到以下代码(来源: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/

相关文章:

c - Gtk 断言失败 c gtk_calendar

关于 malloc array of struct 的困惑

c++ - 如何计算下面的struct占用的内存空间?

go - 将 map 嵌入到go语言的结构中

ios - 面向协议(protocol)的编程示例在 swift 3.0 中不起作用

c - 如何使用函数在 header 中声明并在源代码中定义的结构

c - 如何从一个文件中读取多个问题?

c - 当我尝试运行我的程序时,为什么它总是崩溃?

c - 为了安全起见,我应该始终动态分配数组吗?

arrays - 有没有办法在不使用循环的情况下将结构转换为数组?