《C++ 108好库》之1 chrono时间库和ctime库
《C++ 108好库》之1 chrono时间库和ctime库
- C++ chrono时间库和ctime库
- 1. 时钟 (Clocks):表示时间源,提供当前时间点:
- 2. 时间间隔 (Durations):表示时间长度,由数值和单位组成:
- 3. 时间点 (Time Points):表示特定时间点:
- ctime库
- 总结
C++ chrono时间库和ctime库
std::chrono是 C++11 引入的标准时间库,提供了精确的时间测量和时间点操作功能。 它基于三个核心概念:时钟(Clocks)、时间点(Time Points) 和时间间隔(Durations)。 时间点(Time Points) 时间点表示一个特定的时间点,通常与某个特定的时钟相关联。 auto now = std::chrono::system_clock::now();持续时间(Durations)
持续时间表示两个时间点之间的时间间隔。
auto duration = std::chrono::seconds(5);
时钟(Clocks)
时钟是时间点和持续时间的来源。C++ 提供了几种不同的时钟,例如系统时钟、高分辨率时钟等。
1. 时钟 (Clocks):表示时间源,提供当前时间点:
std::chrono::system_clock::time_point
std::chrono::steady_clock::time_point
// 系统时钟(可能受系统时间调整影响)
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "Current date and time: " << std::ctime(&now_c);
// 稳定时钟(单调递增,不受系统时间调整影响)
auto start = std::chrono::high_resolution_clock::now();
someFunction();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Function took " << duration.count() << " milliseconds to execute." << std::endl;
// 高精度时钟(最高分辨率)
auto now_high = std::chrono::high_resolution_clock::now();
2. 时间间隔 (Durations):表示时间长度,由数值和单位组成:
// 预定义单位
std::chrono::nanoseconds ns(500); // 500纳秒
std::chrono::microseconds us(1000); // 1000微秒
std::chrono::milliseconds ms(5); // 5毫秒
std::chrono::seconds s(30); // 30秒
std::chrono::minutes m(2); // 2分钟
std::chrono::hours h(1); // 1小时
// 自定义时间单位(1/10秒)
using deciseconds = duration<int, std::ratio<1, 10>>;
deciseconds ds(5); // 0.5秒
//用于休眠
std::this_thread::sleep_for(std::chrono::seconds(1));
3. 时间点 (Time Points):表示特定时间点:
// 获取当前时间点
auto now = steady_clock::now();
// 创建未来时间点
auto future = now + seconds(10);
// 计算时间差
auto diff = future - now; // 返回duration类型
ctime库
chrono只能获得time_point,要想化成字符串等,还需要转换成time_t,再转为字符串
四个与时间相关的类型:clock_t、time_t、size_t 和 tm。
1.类型 clock_t、size_t 和 time_t 能够把系统时间和日期表示为某种整数。
2.结构类型 tm 把日期和时间以 C 结构的形式保存,tm 结构的定义如下:
struct tm {
int tm_sec; // 秒,正常范围从 0 到 59,但允许至 61
int tm_min; // 分,范围从 0 到 59
int tm_hour; // 小时,范围从 0 到 23
int tm_mday; // 一月中的第几天,范围从 1 到 31
int tm_mon; // 月,范围从 0 到 11
int tm_year; // 自 1900 年起的年数
int tm_wday; // 一周中的第几天,范围从 0 到 6,从星期日算起
int tm_yday; // 一年中的第几天,范围从 0 到 365,从 1 月 1 日算起
int tm_isdst; // 夏令时
};
//获取系统时间
std::time_t time_sys_c;
std::time(&time_sys_c); //将系统时间转为字符串Www Mmm dd hh:mm:ss yyyy\n\0
std::cout<<std::ctime(&time_sys_c)<<std::endl;//将系统时间转为tm
struct tm *tm_sys_c=localtime(&time_sys_c);
std::cout<<1900+tm_sys_c->tm_year<<"Y"<< tm_sys_c->tm_mon<<"M"<<tm_sys_c->tm_mday<<"R"<<tm_sys_c->tm_hour<<":"<<tm_sys_c->tm_min<<":"<<tm_sys_c->tm_sec<<std::endl;
总结
用作时间显示用ctime;
用作线程休眠用Durations;