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);
问题是这样的,大多数人都用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);
相关文章推荐
- Unix/Linux环境C编程入门教程(22) C/C++如何获取程序的运行时间
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)?
- js获取当前Unix时间戳
- 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间
- python获取上一个月第一天0点的unix时间戳
- 不同编程语言中获取现在的Unix时间戳
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)?
- 获取Unix时间戳(Unix timestamp):
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)
- php 中的获取时间戳 和unix中的时间戳相差4个小时的解决方法
- 如何获取Unix时间戳[C++]
- unix网络基础-TCP时间获取服务器程序
- 获取UNIX主机当前时间的函数
- VC下获取Unix时间戳
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)
- python获取当前时间对应unix时间戳的方法
- JS获取当前日期时间/JS日期转化为unix时间戳
- 不同编程语言中获取现在的Unix时间戳
- 不同编程语言中获取现在的Unix时间戳
- 如何在不同编程语言中获取现在的Unix时间戳(Unix timestamp)