gettimeofday() -- 获取当前时间(保存在结构体timeval中)【转】

来源:互联网 发布:js求log以10为底 编辑:程序博客网 时间:2024/06/05 16:51

#include <stdio.h>
#include <sys/time.h>

#include <time.h>

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

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

}

(1) struct--timeval
--------------------------------------------------
struct timeval {

    time_t      tv_sec;    
    suseconds_ttv_usec;   
};
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, structtimezone *tz);

    Thefunctions gettimeofday() and settimeofday() can get and set the time as well asa timezone.
    Theuse of the timezone structure is obsolete; the tz argument shouldnormally be specified as NULL.

(3) 运行结果:
--------------------------------------------------

time 1181788367:991487
time 1181788369:991602

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


原创粉丝点击