推荐使用 chrono 获取高精度时间戳,也可用 time_t 获取秒级时间戳,结合 strftime 可格式化输出可读时间。

在C++中获取当前时间戳有多种方式,常用的包括使用标准库中的 、 等。不同方法适用于不同精度和平台需求。以下是几种主流且实用的时间戳获取方式。
使用 chrono 高精度获取时间戳(推荐)
std::chrono 是 C++11 引入的现代时间处理库,适合获取高精度时间戳,单位可以是秒、毫秒、微秒等。
以下代码获取自 Unix 纪元(1970-01-01 00:00:00 UTC)以来的毫秒级时间戳:
#include #include int main() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto millis = std::chrono::duration_cast(duration).count(); std::cout << "当前时间戳(毫秒): " << millis << std::endl; return 0;}
如果只需要秒级时间戳,可将 milliseconds 替换为 seconds。
立即学习“C++免费学习笔记(深入)”;
使用 time_t 和 time() 函数(传统方式)
C 风格的时间函数在 C++ 中依然可用,通过 提供。适用于获取秒级时间戳。
#include #include int main() { std::time_t timestamp = std::time(nullptr); std::cout << "当前时间戳(秒): " << timestamp << std::endl; return 0;}
这种方式简单直接,但只精确到秒,不适合需要更高精度的场景。
格式化输出当前时间(附加技巧)
有时除了时间戳,还需要可读的时间字符串。可以结合 localtime 和 strftime 实现:
#include #include #include int main() { std::time_t now = std::time(nullptr); std::array buffer; std::strftime(buffer.data(), buffer.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now)); std::cout << "当前时间: " << buffer.data() << std::endl; return 0;}
这不会改变时间戳本身,但有助于调试和日志记录。
基本上就这些常用方法。对于新项目,建议优先使用 chrono,它更安全、类型更清晰、支持高精度。老项目或简单场景可用 time()。根据实际需求选择合适的方式即可。
以上就是c++++如何获取当前时间戳_c++时间函数与时间戳获取方式的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1483668.html
微信扫一扫
支付宝扫一扫