linux系统编程第10章-时间

来源:互联网 发布:苏州相城淘宝培训 编辑:程序博客网 时间:2024/05/21 14:05

0.时间定义:
真实时间:度量真实时间的起点有两种,一为某个标准点,称为日历时间(calendar),比如UTC时间。二为进程周期的某个固定点,一般为程序启动的时间点,称为流逝时间(elapse)或者墙上时间(wall clock)。
进程时间:一个进程所使用的cpu时间总量。
1.日历时间:
系统调用gettimeofday()可以获取日历时间。

#include<sys/time.h>int gettimeofday(struct timeval *tv, struct timezone *tz);struct timeval {  time_t      tv_sec;//seconds since 00:00:00 1 Jan 1970 UTC  suseconds_t tv_usec;}timezone为历史遗留问题,都置为NULL:

另外一个系统调用time()返回秒数,没有微秒的数据,所以一般不用了。
上面两个函数都是返回的UTC时间,就是从1970年1月1日0点到现在的秒数。
2.时间转换函数:
a.将time_t转为可打印格式:char *ctime(const time_t *timep),返回事例为:Wed Jun 8 14:22:10 2011. 存储在静态空间。
b.time_t 和分解时间之间的转换
gmtime()和localtime()可将time_t值转为一个分解时间(broken-down time)。注意,只是转换,所以使用这两个函数之前,需要通过time()函数或者gettimeofday()函数来获得现在的UTC秒数,然后调用这两个函数转换为下面的时间格式。

#include<time.h>struct tm *gmtime(const time_t *timep);//UTC的分解时间struct tm *localtime(const time_t *timep);//考虑了时区的本地时间。struct tm {  int tm_sec;//Seconds(0-60)  int tm_min;//Minutes(0-59)  int tm_hour;//Hours(0-23)  int tm_mday;//Day of the month(1-31)  int tm_mon;//Month(0-11)  int tm_year;//Year since 1900  int tm_wday;//Day of the week(Sunday = 0)  int tm_yday;//day in the year (0-365; 1 Jan = 0)  int tm_isdst;//>0 dst in effect.==0 not effect, < 0 not available}time_t mktime(struct tm *timeptr);//将分解时间合并成time_t时间。如果tm_isdst为0,则视为标准时间,忽略夏令时。如果> 0,则视为夏令时。<0则试图判定dts在每年的这一时间是否生效。char *asctime(const struct tm *timeptr);//将分解时间转换为打印格式。size_t strftime(char *outstr, size_t maxsize, const char *format, const struct tm *timeptr);//将分解时间转化为打印格式,并且可以通过format定义字符串的格式。格式定义在P158#define _XOPEN_SOURCEchar *strptime(const char *str, const char *format, struct tm *timeptr);//strftime的逆函数,将包含日期和时间的字符串转换成分解时间。

3.时区:
a.时区信息保存在/usr/share/zoneinfo中,里面定义了一些时区名称。系统的本地时间由时区文件/etc/localtime定义,通常链接到/usr/share/zoneinfo下的一个文件。
b.利用环境变量TZ可以指定一个时区。格式为冒号和时区名称组成。
比如 export TZ=”:Pacific/Auckland”
4.地区:locale
地区信息维护于/usr/share/local目录下。locale命令可以显示当前地区环境。locale -a可以列出系统定义的整套地区。可以利用setlocale()函数来设置和查询当前的地区。
5.更新系统时间:

#define _BSD_SOURCE#include <sys/time.h>int settimeofday(const struct timeval *tv, const struct timezone *tz);//tz 设置为NULL。该函数会直接改变时间,造成时间的突然变化,可能会影响某些应用程序的运行。int adjtime(struct timeval *delta, struct timeval *olddelta);//这个函数是慢慢的微调,可以为正为负。6.软件时钟:软件时间的精度称为jiffies。单位一般为HZ。7.进程时间:进程时间是进程创建后使用的cpu时间的数量。分为用户cpu时间和系统(内核)cpu时间。time命令可以获取某个进程的进程时间$time ./myprogreal Om4.84suser Om1.030ssys Om3.43s系统调用times()可以获得进程时间。clock()系统调用返回一个描述调用进程所用的总的cpu时间。包括用户和系统。
0 0
原创粉丝点击