如何在跨平台 c++ 32 位系统中获取以毫秒为单位的时差

How to get a time difference in milliseconds in a cross platform c++ 32-bit system?

本文关键字:获取 为单位 时差 系统 跨平台 c++      更新时间:2023-10-16

我正在为跨平台的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>  

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

这是一种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演示

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

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

high_resolution_clock演示

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

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

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