c++ - c ++获取毫秒时间
问题描述
我想在一秒钟后获取包含六位数字的日期和时间,例如 2017-07-03 15:01:01.123456。如何得到它?我尝试使用 time timeval 和 gettimeofday,但出现错误。我的代码:
time_t timer;
char timestr[29];
struct timeval *tm_info;
time(&timer);
tm_info = gettimeofday(&timer);
strftime(timestr, 29, "%Y-%m-%d %H:%M:%S", tm_info);
ss << timestr;
解决方案
首先,如果您想要当前秒的六位小数分辨率,我们讨论的是微秒 ( 1us = 10E-6
),而不是毫秒 ( 1ms = 10E-3
)。此外,您可能应该使用std::chrono
,因为gettimeofday()
它是特定于 Linux 的操作系统,并且不适用于其他系统。
要获取您可以使用的日期<time.h>
及其gmtime()
(UTC),它会返回一个struct tm
. 至于时间,获取当前秒后经过的时间(以微秒为单位)的一种简单方法是利用分辨率仅为 1秒14:31:09.590721
的事实:time_t
#include <iostream>
#include <string>
#include <chrono>
#include <time.h>
int main() {
for (int i = 0; i < 1000; ++i) {
auto now = std::chrono::system_clock::now();
auto now_t = std::chrono::system_clock::to_time_t(now);
//Exploit now_t (time_t): resolution is only 1 second - get microseconds
auto dur = now - std::chrono::system_clock::from_time_t(now_t);
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(dur).count();
//Print the date and time as yyyy-mm-dd hh::mm::ss.xxxxxx
tm& now_tm = *(gmtime(&now_t));
std::string year = std::to_string(now_tm.tm_year + 1900) + "-";
std::string mon = std::to_string(now_tm.tm_mon + 1) + "-";
std::string day = std::to_string(now_tm.tm_mday) + " ";
std::string hour = std::to_string(now_tm.tm_hour);
std::string min = std::to_string(now_tm.tm_min);
std::string sec = std::to_string(now_tm.tm_sec);
if (hour.size() == 1) hour.insert(0, "0");
if (min.size() == 1) min.insert(0, "0");
if (sec.size() == 1) sec.insert(0, "0");
std::cout << year << mon << day
<< hour << ":" << min << ":" << sec << "." << micros << "\n";
}
return 1;
}
在我的时区运行 10 次迭代给出:
2018-5-4 12:36:11.47578
2018-5-4 12:36:11.48663
2018-5-4 12:36:11.49516
2018-5-4 12:36:11.50392
2018-5-4 12:36:11.51261
2018-5-4 12:36:11.52455
2018-5-4 12:36:11.53316
2018-5-4 12:36:11.54213
2018-5-4 12:36:11.55113
2018-5-4 12:36:11.55969
PS:当您处于这种粒度时,您应该知道时钟源精度/漂移。这取决于系统(硬件、操作系统等)。严格的计时需要特殊的硬件(例如 GPSDO)和软件。
推荐阅读
- node.js - 第一次使用 node.js X 未定义
- python - 在python中的字符串匹配后无法删除行
- javascript - 返回映射行 NULL
- systemjs - 如何在我的 angular9 项目中使用 SystemJS
- python - 设置一定百分比的数据帧等于 NaN
- elasticsearch - 禁用对象中的 ElasticSearch 查询字段
- javascript - 使用 Node.js 将文件名转换为时间戳
- html - 在 Angular 中按下提交按钮时观察值的变化
- python - tkinter 标签周围没有白框
- mysql - useSelector 函数没有更新调度函数后的状态 -react hooks