预备知识:
(1) struct--timeval
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};
millisecond 毫秒
microsecond 微秒
timeval表示一个时间点,比如:
timeval.tv_sec = 1 (s)
timevat.tv_usec = 500 000 (μs)
1:500 = 1s500000μs = 1.5s
(2) gettimeofday() -- 获取当前时间(保存在结构体timeval中)
int gettimeofday(struct timeval *tv, struct timezone *tz);
gettimeofday()会把目前的时间有tv所指的结构返回,当地时区的信息则放到tz所指的结构中。
timezone 结构定义为:
struct timezone{
int tz_minuteswest;
int tz_dsttime;
};
程序清单:
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main(int argc,char *argv[])
{
struct timeval tv;
while(1)
{
gettimeofday(&tv,NULL);
printf("time %u:%un",tv.tv_sec,tv.tv_usec);
sleep(3); //每隔三秒打印一次
}
return 0;
}
|
编译并运行程序:
obe-240 eagle/test> gcc -o time2 time2.c
obe-240 eagle/test> ./time2
time 1292238953:795849
time 1292238956:795906
time 1292238959:799892
time 1292238962:803878
time 1292238965:807863
time 1292238968:811848
time 1292238971:815834
time 1292238974:819820
time 1292238977:823805
time 1292238980:827792
time 1292238983:831777
time 1292238986:835762
阅读(1067) | 评论(0) | 转发(0) |