在 C 中使用 timeval 结构需要帮助 [英] Help required with timeval structure in C

查看:32
本文介绍了在 C 中使用 timeval 结构需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算运行某个函数所需的时间并遇到以下代码(来源:http://snippets.dzone.com/posts/show/4254 )声称...记录并输出一段代码的执行时间(以微秒为单位)"

I needed to calculate the time it takes to run a certain function and ran into the following code (source: http://snippets.dzone.com/posts/show/4254 ) with the claim that "...record & output the execution time of a piece of code in microseconds"

/* 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);

但我对这段代码的个人经验表明,输出时间"以秒而不是微秒为单位.我需要一些关于我是对还是错的意见(我需要一劳永逸地澄清这一点).

but my personal experience with the piece of code shows that the output 'time' is in seconds instead of microseconds. I need some input on whether I am right or wrong (I need to clarify this once and for all).

推荐答案

你说得对.

结构体的tv_sec成员存储秒,tv_usec成员(微秒)除以10^6转换为秒.

The tv_sec member of the structure stores seconds, and the tv_usec member (microseconds) is converted to seconds by dividing by 10^6.

这篇关于在 C 中使用 timeval 结构需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆