c++ 的时间函数定义在 <ctime>(time.h) 文件中
文件中常量:
CLOCKS_PER_SEC: 官方描述: Clock ticks per second (macro )
正是因为这个每秒滴答数的定义不同,在Linux 和windows 平台下会产生不同的时间表述方法,所以不建议使用这个类的函数来计算时间差,而是希望采用 chrono 库来计算
NULL:
- 文件中类型:
- time_t: 表示自UTC(1970年1月1日)00:00小时起经过的秒数 time() 函数产生
- clock_t: 表示时钟的滴答数,恒定于系统的每秒嘀嗒数
- tm: 结构体
- struct tm {
int tm_sec; /* 秒 - [0,59] */
int tm_min; /* 分钟 - [0,59] */
int tm_hour; /* 小时 - [0,23] */
int tm_mday; /* 天 - [1,31] */
int tm_mon; /* 月 - [0,11] */
int tm_year; /* 年 */
int tm_wday; /* 星期几(周日开始) - [0,6] */
int tm_yday; /* 天 - [0,365] */
int tm_isdst; /* 夏令时标志 */
}; - 相关操作函数:
- time() :
- 获取time_t 类型的时间
- mktime():
- 将 tm 结构体转成 time_t 类型的时间
- difftime()
- 计算两个time_t 时间差
- clock():
- 获取计算机平台的嘀嗒数
- 相关转换函数:
- asctime():
- tm 结构时间转成字符串
- ctime();
- time_t 时间转成字符串输出
- gmtime()
- time_t 时间转成UTC时间的 tm格式输出
- localtime()
- time_t 时间转成本地时间的tm 格式输出
- strftime():
- 格式化tm格式的字符串
- 代码比较
cout << "ctime / time.h 类测试 函数" << std::endl; cout << "常量:" << std::endl; cout << CLOCKS_PER_SEC << endl; time_t current_time = time(0); // 表示自UTC(1970年1月1日)00:00小时起经过的秒数 time() 函数产生 clock_t begin = clock(); // 获取计算机的嘀嗒数 struct tm *current_utf_time = gmtime(¤t_time); struct tm *current_local_time = localtime(¤t_time); cout << "time_t is : " << current_time << endl; cout << "clock is : " << begin << endl; cout << "time_t 转成字符串 : " << ctime(¤t_time) << endl; cout << "struct UTC tm 转成字符串 : " << asctime(current_utf_time) << endl; cout << "struct local tm 转成字符串 : " << asctime(current_local_time) << endl; struct tm y2k = { 0 }; y2k.tm_sec = 0; y2k.tm_min = 0; y2k.tm_hour = 0; y2k.tm_mday = 1; y2k.tm_mon = 0; y2k.tm_year = 100; double seconds = difftime(current_time, mktime(&y2k)); cout << "距离 2000 01/01 00:00:00 时间秒数为:" << seconds << endl; time_t end_time = time(0); clock_t end = clock(); cout << "time_t 时间差 :" << (end_time - current_time) << "s" << endl; cout << "clock 时间差为 : " << (end - begin) / CLOCKS_PER_SEC << "s" << endl; char buffer[80]; strftime(buffer, 80, "Now it\'s %I:%M%p.", current_utf_time); cout << buffer << endl;
运行完上面的标准库后,你会惊喜的发现,编译中有一些安全警告,建议你在更换这些方法