C语言有关time的函数小结

来源:互联网 发布:修道入门 知乎 编辑:程序博客网 时间:2024/06/05 00:59

头文件 time.h
函数用途 函数名
得到处理器时间 clock
得到时间差 difftime
设置时间 mktime
得到时间 time
得到以ascII码表示的时间 asctime
得到以字符串表示的时间 ctime
得到指定格式的时间 strftime
UTC 世界标准时间(格林尼治时间)
Calendar Time 日历时间(从某个时间点到现在的秒数)
epoch 时间点(也是日历时间)
clock tick 时钟周期

一、计时:clock()函数
clock_t clock();
返回从“开始这个程序进程”到“程序中调用clock()函数”之间的时钟周期数

在time.h中,clock_t的定义为#define _CLOCK_T_DEFINEDtypedef long clock_t;#define _CLOCK_T_DEFINE#endif在time.h中,还定义了一个常量“CLOCKS_PER_SEC”,即每秒的时钟周期数,就是频率可以使用clock()/CLOCK_PER_SEC来计算一个进程自身运行时间时钟周期数 / 单位时间(S)内的时钟周期数 = 运行时间(秒数)

二、与日期和时间相关的数据结构
首先是
struct tm{
int tm_sec; //秒
int tm_min; //分
int tm_hour; //时
int tm_mday; //天(1-31)
int tm_mon; //月
int tm_year; //年
int tm_wday; //星期
int tm_yday; //从每年一月一日开始天数(0-365),0代表1月1日
int tm_isdst; //夏令时标志
};
使用tm结构时间为分解时间(broken-down time)

再来说明Calendar Time,日历时间,类型为time_t,是从1970年1月1日00:00:00到现在秒数,同样定义在time.h中    #define _TIME_T_DEFINE    typedef long time_t;    #define _TIME_T_DEFINED    #endif同时在time.h中,还有一些函数double  difftime(time_t  time1, time_t time0);time_t  mktime(struct  tm* timeptr);time_t  time(time_t* timer);char* asctime(const  struct  tm* timeptr);char* ctime(const  time_t* timer);

很重要,使用方法:
第一步:通过time()函数获得当前的日历时间(秒数),time()接受的参数是一个time_t类型对象的地址,其时间值就存在传入的地址上,当然,也可以传入空指针,这种情况下,只能通过返回机制来提供值;
time_t now;
time(&now);
now = time(NULL); //now就是现在的日历时间,从1970年到现在的秒数

第二步:获得日期与时间1.(tm结构的时间)    函数struct tm* gmtime(const time_t* timer);     struct tm* localtime(const time_t* timer);    这两个函数区别在于gmtime()将秒数转化为格林尼治时间,并返回一个tm结构保存这个时间;而localtime()将秒数    转化为本地时间。例:struct tm* worldtime;struct tm* localtime;time_t t;t=time(NULL);worldtime=gmtime(&t);localtime=localtime(&t);获取日期与时间2.(以年月日时分秒格式)    函数char* asctime(const struct tm* timeptr);      char* ctime(const time_t* timer);    其中asctime通过tm结构体获得固定格式时间    而ctime通过秒数获取固定格式时间例:printf(ctime(&t));等价于:struct tm* ptr;ptr = localtime(&t);printf(asctime(ptr));例:struct tm* ptr;time_t it;it = time(NULL); //获取秒数ptr = gmtime(&it); //gmtime返回格林尼治时间并存在ptr指向的结构体printf(asctime(ptr)); //以年月日时分秒显示了世界时间 printf(ctime(&it));  //以年月日时分秒显示了本地时间

自定义时间格式:strftime()函数可以将时间自定义格式
size_t strftime(char* strDest, size_t maxsize,
const char* format, const struct tm* timeptr);
说明:根据format定义的格式把timeptr中保存的信息存入strDest指向的字符串,最多可以向strDest中存放maxsize个字符,返回strDest指向的字符串中放置的字符数。

将tm结构的时间转化为秒数
time_t mktime(struct tm* timeptr);
例:
#include

原创粉丝点击