c++中获取系统时间常用chrono和ctime;2. chrono精度高、类型安全,适合C++11及以上;3. ctime简单兼容好,适合传统代码;4. 高精度用chrono,快速格式化可用ctime配合strftime;5. 多线程注意localtime线程安全问题。

在C++中获取当前系统时间,常用的方法有两种:使用标准库
使用 获取高精度系统时间
chrono 是C++11引入的时间处理库,提供纳秒级精度,支持时钟、时间点和时间间隔的抽象。
获取当前时间并格式化为年-月-日 时:分:秒:
#include <iostream> #include <chrono> #include <iomanip> #include <sstream> <p>std::string getCurrentTime() { auto now = std::chrono::system_clock::now(); auto time_t = std::chrono::system_clock::to_time_t(now);</p><pre class='brush:php;toolbar:false;'>std::stringstream ss; ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S"); return ss.str();
}
立即学习“C++免费学习笔记(深入)”;
说明:
- system_clock::now() 获取当前时间点
- to_time_t() 转换为传统的 time_t 类型
- std::put_time 配合流操作进行格式化输出
- 需要包含
支持 put_time
若需毫秒或微秒精度,可提取时间点中的额外部分:
auto now = std::chrono::system_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch()) % 1000;
使用 快速获取当前时间
ctime 是C风格头文件,使用简单,适合不需要高精度的场景。
#include <iostream> #include <ctime> <p>void printCurrentTime() { std::time_t t = std::time(nullptr); char* timeStr = std::ctime(&t); std::cout << "当前时间: " << timeStr; }</p>
说明:
- std::time(nullptr) 获取当前时间的秒数(自1970-01-01)
- std::ctime() 将 time_t 转为字符串,自动换行
- 输出格式固定为 “Wed Jun 12 15:30:45 2024n”
如需自定义格式,使用 std::strftime:
char buffer[100]; std::tm* tm = std::localtime(&t); std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm); std::cout << buffer << std::endl;
chrono 与 ctime 的选择建议
项目中如何选择?看需求:
- 需要毫秒、微秒精度 → 用 chrono
- 做时间差计算、延时控制 → chrono 更直观安全
- 快速打印日志时间戳 → ctime + strftime 更简洁
- 跨平台且要求现代C++风格 → 优先 chrono
- 维护旧代码或嵌入式资源紧张 → 可用 ctime
基本上就这些。两种方法都能有效获取系统时间,根据项目环境和精度要求灵活选用即可。注意多线程下 localtime 非线程安全,必要时用 localtime_s(windows)或 localtime_r(linux)。