Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
C++如何获取当前系统时间_C++ chrono库与ctime用法详解_创想鸟

C++如何获取当前系统时间_C++ chrono库与ctime用法详解

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

c++如何获取当前系统时间_c++ chrono库与ctime用法详解

在C++中获取当前系统时间,常用的方法有两种:使用标准库 和传统的 。两者各有特点,chrono 更现代、类型安全、精度高,适合C++11及以上项目;而 ctime 简单直接,兼容性好,常用于传统代码或快速开发。

使用 获取高精度系统时间

chrono 是C++11引入的时间处理库,提供纳秒级精度,支持时钟、时间点和时间间隔的抽象。

获取当前时间并格式化为年-月-日 时:分:秒:

#include #include #include #include 

std::string getCurrentTime() {auto now = std::chrono::system_clock::now();auto time_t = std::chrono::system_clock::to_time_t(now);

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(           now.time_since_epoch()) % 1000;

使用 快速获取当前时间

ctime 是C风格头文件,使用简单,适合不需要高精度的场景。

#include #include 

void printCurrentTime() {std::time_t t = std::time(nullptr);char* timeStr = std::ctime(&t);std::cout << "当前时间: " << timeStr;}

说明:

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)。

以上就是C++如何获取当前系统时间_C++ chrono库与ctime用法详解的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488654.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
c++ 随机数生成方法 c++ rand函数用法教程
上一篇 2025年12月19日 11:44:17
C++的Concept和Interface有什么区别_C++20 Concepts与传统面向对象接口的对比
下一篇 2025年12月19日 11:44:32

相关推荐

发表回复

登录后才能评论
关注微信