Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1338729
  • 博文数量: 198
  • 博客积分: 1629
  • 博客等级: 上尉
  • 技术积分: 2743
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-01 15:41
文章分类
文章存档

2023年(6)

2022年(20)

2021年(8)

2020年(3)

2018年(17)

2017年(3)

2016年(3)

2015年(9)

2014年(13)

2013年(17)

2012年(77)

2011年(22)

分类: LINUX

2012-06-01 10:42:04

gettimeofday() -- 获取当前时间(保存在结构体timeval中)
#include
#include
#include

int main(int argc, char * argv[]){

    struct timeval tv;                //(1)
    while(1){
        gettimeofday(&tv, NULL);      //(2)
        printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);
        sleep(2);
    }
    return 0;
}

(1) struct--timeval
--------------------------------------------------
struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};
millisecond        毫秒
microsecond        微秒

timeval表示一个时间点,比如:
timeval.tv_sec = 1   (s)
timevat.tv_usec = 500 000 (μs)
1:500 = 1s500000μs = 1.5s

(2) gettimeofday()
--------------------------------------------------
int gettimeofday(struct timeval *tv, struct timezone *tz);

    The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone. 
    The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.

(3) 运行结果:
--------------------------------------------------
time 1181788367:991487
time 1181788369:991602

表示睡眠2秒经过的精确时间为: 2s115μs

备注:
1秒=1000毫秒,
1毫秒=1000微秒,
1微妙=1000纳秒,
1纳秒=1000皮秒。
秒用s表现,毫秒用ms,微秒用μs表示,纳秒用ns表示,皮秒用ps表示。
阅读(3098) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~