【问题标题】:Get time with milliseconds in C++17?在 C++17 中以毫秒为单位获取时间?
【发布时间】:2020-07-22 11:36:16
【问题描述】:

如何使用 boost 或标准库在 C++17 中获取当前时间(以毫秒为单位)?我尝试使用 std::chrono:

int main()
{
    const auto currentDateTime = std::chrono::system_clock::now();
    const auto currentDateTimeTimeT = std::chrono::system_clock::to_time_t(currentDateTime);
    const auto currentDateTimeLocalTime = *std::gmtime(&currentDateTimeTimeT);

    char currentDateTimeArrStr[100];
    std::strftime(currentDateTimeArrStr, 100, "%Y%m%d_%H%M%S.%f", &currentDateTimeLocalTime);

    std::clog << std::string(currentDateTimeArrStr) << std::endl;
}

%f 格式仅在 python 中实现 strftime 函数而不是在 C++ 中,并且带有 boost:

int main()
{
    const auto date = boost::gregorian::day_clock::universal_day();
    boost::gregorian::date d(date.year(), date.month(), date.day());
    const auto time = boost::posix_time::second_clock::universal_time().time_of_day();
    boost::posix_time::time_duration td(time.hours(), time.minutes(), time.seconds(), time.fractional_seconds());
    std::stringstream ss;
    ss << d << ' ' << td;
    boost::posix_time::ptime pt(not_a_date_time);
    ss >> pt;
    std::cout << pt << std::endl;
}

但是 boost api 只给total_milliseconds

我需要这样的输出:12:02:34.323232

【问题讨论】:

  • 你说你需要像12:02:34.323232这样的输出。当然,这意味着您需要以微秒为单位的时间(有 6 个小数位 - 毫秒只有 3 个小数位)。

标签: c++ time c++17 chrono milliseconds


【解决方案1】:

所以只需打印时间点的毫秒数...

const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000;
std::clog << std::put_time(&currentDateTimeLocalTime, "%Y%m%d_%H%M%S") 
    << "." << std::setfill('0') << std::setw(3) << ms << std::endl;

如何在 C++11 中以毫秒为单位获取当前时间

您已经在std::chrono::system_clock::now() 通话中获得了当前时间。

【讨论】:

  • 谢谢,但我需要 5 位毫秒的精度。
  • 那不是毫秒 :D 并且“精度”不是“分辨率”,对于精度,请您的系统经销商给您更多的精度,即。寻找更精确的时钟源。 5 位毫秒值,即10000 ms 将等于 10 秒。
  • 如果您希望输出的分辨率为 10 微秒,那么只需将时间点转换为微秒,然后将结果除以 10 并得到模 10000。
  • 感谢转换为微秒和纳秒,我想得到我想要的,但是例如使用这个 python 脚本datetime.utcnow().strftime("%Y%m%d_%H%M%s.%f") 我得到像'20200722_12011595433689.367198' 这样的输出,这是我在 C++ 中想要的。
  • 但 C++ 不支持 %f。所以...好吧..我想您可以编写自己的 strftime 实现来支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
相关资源
最近更新 更多