struct timeval结构体 以及 gettimeofday()函数

一、struct timeval结构体
struct timeval结构体在time.h中的定义为:
  1. struct timeval
  2. {
  3. __time_t tv_sec;        /* Seconds. */
  4. __suseconds_t tv_usec;  /* Microseconds. */
  5. };
其中,tv_sec为Epoch到创建struct timeval时的秒数,tv_usec为微秒数,即秒后面的零头。比如当前我写博文时的tv_sec为1244770435,tv_usec为442388,即当前时间距Epoch时间1244770435秒,442388微秒。需要注意的是,因为循环过程,新建结构体变量等过程需消耗部分时间,我们作下面的运算时会得到如下结果:
  1. #include <sys/time.h>
  2. #include <stdio.h>
  3.   
  4. int
  5. main(void)
  6. {
  7.         int i;
  8.         struct timeval tv;

  9.         for(= 0; i < 4; i++){
  10.                 gettimeofday(&tv, NULL);
  11.                 printf("%d\t%d\n", tv.tv_usec, tv.tv_sec);
  12.                 sleep(1);
  13.         }

  14.         return 0;
  15. }
  1. 329612 1314851429
  2. 329782 1314851430
  3. 329911 1314851431
  4. 330036 1314851432
前面为微秒数,后面为秒数,可以看出,在这个简单运算中,只能精确到小数点后面一到两位,或者可以看出,每进行一次循环,均需花费0.005秒的时间,用这个程序来作计时器显然是不行的,除非精确计算产生的代码消耗时间。

二、gettimeofday()函数
原型:
  1. /* Get the current time of day and timezone information,
  2.    putting it into *TV and *TZ. If TZ is NULL, *TZ is not filled.
  3.    Returns 0 on success, -on errors.
  4.    NOTE: This form of timezone information is obsolete.
  5.    Use the functions and variables declared in <time.h> instead. */
  6. extern int gettimeofday (struct timeval *__restrict __tv,
  7.                          __timezone_ptr_t __tz) __THROW __nonnull ((1));
gettimeofday()功能是得到当前时间和时区,分别写到tv和tz中,如果tz为NULL则不向tz写入。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值