c++ - 在 Visual Studio 2017 中使用 high_resolution_clock 获取错误的日期和时间/从纪元时间获取毫秒数(1970 年 1 月 1 日)

标签 c++ visual-studio c++11 time

我在使用 Visual Studio 2017 时遇到问题。

我正在尝试以毫秒分辨率获取当前时间和日期。我在几个编译器中尝试了以下代码:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
using namespace chrono;

int main()
{

    high_resolution_clock::time_point p = high_resolution_clock::now();
    milliseconds ms = duration_cast<milliseconds>(p.time_since_epoch());
    seconds s = duration_cast<seconds>(ms);
    time_t t = s.count();
    cout << ctime(&t) << "\n";
    cin.ignore(1);
}

除 Visual Studio 2017 之外的每个编译器都会打印正确的时间。 Visual Studio 的输出是:

Tue Jan 6 07:28:21 1970

MinGW 输出:

Sun Feb 03 18:01:38 2019

有没有办法修复代码,使其在所有编译器中都能正常工作?我需要 high_resolution_clock 才能访问毫秒。

最佳答案

high_resolution_clock是具有最高分辨率的时钟的别名:

Class std::chrono::high_resolution_clock represents the clock with the smallest tick period provided by the implementation. It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.

这可以解释您在不同编译器上的不同时间。

steady_clock不保证给出有意义的时间,但有助于跟踪时间:

This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals. Is there any way to fix the code so that it works in all compilers correctly? I need high_resolution_clock to have access to milliseconds.

system_clock代表您操作系统的时钟:

Class std::chrono::system_clock represents the system-wide real time wall clock.

It may not be monotonic: on most systems, the system time can be adjusted at any moment. It is the only C++ clock that has the ability to map its time points to C-style time, and, therefore, to be displayed (until C++20).

如果您需要日期或时间点的毫秒数,请使用 std::chrono::system_clock,但如果您只需要跟踪耗时,请使用 std::chrono::high_resolution_clock。

获取自 system_clock 开始以来的毫秒数:

auto timePoint = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
                                    (timePoint.time_since_epoch());
std::cout << "since epoch: " << ms.count() << " ms";

上面的代码片段应该适用于大多数操作系统和编译器,尽管不能保证 time_since_epoch 返回自 1970 年以来的时间,但只能返回自时钟纪元以来的时间,这在大多数情况下是您想要的行为。

关于c++ - 在 Visual Studio 2017 中使用 high_resolution_clock 获取错误的日期和时间/从纪元时间获取毫秒数(1970 年 1 月 1 日),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503887/

相关文章:

c++ - 为 iOS 编译 OpenFST 时出现转换错误

c++ - STL列表-[intNumber]的作用是什么?

c++ - 图问题 : Find whether two nodes share the same branch in O(1) time and O(1) storage per node

visual-studio - 在 Visual Studio 2017 中使用 64 位 Visual C++ 工具集

c++ - 为什么 weak_ptr 没有比较运算符==?

C++ Bimap 左 unordered_map 右排序可变 multimap

c# - Visual Studio 项目需要哪些文件?

c# - 如何使用 C# 和 Visual Studio 解决自动化 UI 测试中的计时问题?

c++ - 如何编写替换链式方法调用的可变参数方法?

c++ - 如何使用智能指针跟踪类的对象?