如何在跨平台 c++ 32 位系统中获取以毫秒为单位的时差
How to get a time difference in milliseconds in a cross platform c++ 32-bit system?
我正在为跨平台的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 位系统上的工作方式完全相同。
相关文章:
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 如何在没有硬编码的情况下以C++为单位获取类数组的长度?
- 获取嵌套 stl 容器的大小(以字节为单位)
- 可视化 如何获取图像中像素的颜色(以C++ (sfml) 为单位)
- 在Windows上获取OpenGL点大小(以像素为单位)?
- 仅使用C++中的标准库获取以毫秒为单位的当前日期和时间
- 如何使用闰秒以微秒为单位获取 UTC 时间
- 获取C++模板参数包的总大小(以字节为单位)
- tiny-utf8:以字符/代码点为单位获取偏移量
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 如何在C++中以毫秒为单位获取今天的 UTC 午夜时间?
- 如何在跨平台 c++ 32 位系统中获取以毫秒为单位的时差
- 获取字符串的长度(以C++为单位)
- C++-获取以整数位为单位的大小
- 获取系统时间(以毫秒为单位)作为int/double
- 如何获取自C++纪元 (MSVS) 以来的本地当前时间(以秒为单位)
- 如何从1970年1月1日(C++)开始获取当前系统时间(以毫秒为单位)
- 以 C++ 为单位获取当前时间(以月/日/年为单位)
- 如何以毫秒为单位获取自 1970 年以来的当前时间戳,就像 Java 一样
- 在 c++ 中获取以毫秒为单位的时差