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

dk1*_*k13 1 c++ timestamp 32-bit milliseconds

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

std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
Run Code Online (Sandbox Code Playgroud)

或系统使用

#include <sys/time.h>  
Run Code Online (Sandbox Code Playgroud)

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

rus*_*tyx 5

这是一个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;
}
Run Code Online (Sandbox Code Playgroud)

system_clock演示

Time since epoch: 1486930917677
Time difference in milliseconds: 0
Time difference in nanoseconds: 102000
Run Code Online (Sandbox Code Playgroud)

对于标准具有的高分辨率时间点差异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
Run Code Online (Sandbox Code Playgroud)

请记住,high_resolution_clock2015年之前Visual Studio的精度仍然是1秒.它在Visual Studio 2015+中具有100ns的精度,并且在其他平台上应该具有至少1ms的精度.

PS std::chrono在32位和64位系统上的工作原理完全相同.