您的位置:首页 > 其它

unix获取时间至毫秒精度

2007-06-10 11:49 190 查看
看网上提出这类问题 的帖子很多。
问题是这样的,大多数人都用ctime这样的函数来实现获取本地时间的time_t值。但是微秒的类型是suseconds_t类型。秒都time_t类型来存储。显然ctime无法处理时间到毫秒的信息。有一个gettimeofday的函数,我们来看一下这个函数的原型。
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval 这个结构定义如下:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
很显然他里面包括了秒和微秒的信息。来看看这个换算公式 1秒=1000毫秒=1000000微秒 有了这个公式我们就能很方便的计算出相应的毫秒值了。
struct timezone 这个结构是用来说明时区的。
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
可以用来获取主机的时区信息。具体的常量定义可以参阅man手册
gettimeofday函数会自动填充上面这两个结构。

time_t now; struct timezone tz; struct timeval tv; struct tm *ptime; if(gettimeofday(&tv,&tz)<0){ perror("gettimeofday"); exit(-1); } /*下面可以用时间转换函数来转换time_t*/ ptime=localtime(&(tv.tv_sec)); printf("localtime is:/n %s/n",asctime(ptime)); printf("micorseceond is :%d/n",tv.tv_usec);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: