【问题标题】:How to get a time difference in milliseconds in a cross platform c++ 32-bit system?如何在跨平台 c++ 32 位系统中获得以毫秒为单位的时间差?
【发布时间】:2017-02-12 19:12:03
【问题描述】:

我正在为跨平台 32 位嵌入式系统(windows 和 linux)开发一个 c++ 应用程序。对于一个需要的功能,我需要以毫秒为单位计算时间差。首先,纪元时间戳为 32 位系统提供的最大精度是一秒。我遇到的大多数相关答案要么与 64 位相关,例如使用 std::clock 或 std::chrono,例如:

std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();

或系统特定使用

#include <sys/time.h>  

或 Windows 上的 GetSystemTime 函数。我还检查了与 poco 相关的时间函数,但它们也基于使用 64 位变量。这可以使用现有的标准或外部 c++ 库来完成,还是我应该采用不同的方法?

【问题讨论】:

  • 您需要以毫秒为单位的纪元时间还是需要以毫秒为单位的两个时间点之间的差异?
  • @RustyX 我需要以毫秒为单位的两个时间点之间的差异,但我假设如果我可以在不同的时间点以毫秒为单位获得纪元时间也可以完成这项工作,除非我错过了什么。
  • 没有标准的可移植方式来获取以毫秒为单位的纪元时间。 chrono::system_clock 的精度通常为 1 秒,chrono::high_resolution_clock 不是从纪元开始的。
  • @RustyX 好的,那么两个时间点之间的简单差异(以毫秒为单位)就足够了。

标签: c++ timestamp 32-bit milliseconds


【解决方案1】:

这是一种以毫秒为单位获取纪元时间和时间差的 C++11 方法(好吧,std::literals 是 C++14,但您不必使用它):

#include <iostream>
#include <chrono>

using namespace std::literals;

int main()
{
    using Clock = std::chrono::system_clock;
    auto point1 = Clock::now();
    int64_t epoch = point1.time_since_epoch() / 1ms;
    std::cout << "Time since epoch: " << epoch << std::endl;
    auto point2 = Clock::now();
    std::cout << "Time difference in milliseconds: " << ((point2 - point1) / 1ms) << std::endl;
    std::cout << "Time difference in nanoseconds: " << ((point2 - point1) / 1ns) << std::endl;
}

system_clock demo

Time since epoch: 1486930917677
Time difference in milliseconds: 0
Time difference in nanoseconds: 102000

对于高分辨率的时间点差异,标准有chrono::high_resolution_clock,它可能提供比chrono::system_clock更高的精度,但它的纪元通常从系统启动时间开始,而不是从 1970 年 1 月 1 日开始。

high_resolution_clock demo

Time since "epoch": 179272927
Time difference in milliseconds: 0
Time difference in nanoseconds: 74980

请记住,high_resolution_clock 在 2015 年之前在 Visual Studio 上仍具有 1 秒的精度。在 Visual Studio 2015+ 中具有 100ns 的精度,应该在其他平台上至少具有 1 毫秒的精度。

PS std::chrono 在 32 位和 64 位系统上的工作方式完全相同。

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 2015-07-17
    • 2019-08-29
    • 2011-08-27
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    相关资源
    最近更新 更多