繁体   English   中英

使用VC141将high_resolution_clock :: time_point转换为time_t

[英]Convert high_resolution_clock::time_point to time_t with VC141

在Visual Studio 2013中,我只是使用了

#include <chrono>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <sstream>

std::string Time_Point_String(const std::chrono::high_resolution_clock::time_point & timePoint)
{
    time_t timeNow = std::chrono::system_clock::to_time_t(timePoint);

    tm time = *localtime(&timeNow);

    std::stringstream timeString;
timeString << std::setfill('0') << 1900 + time.tm_year << "-" << std::setw(2) << time.tm_mon + 1 << "-" << std::setw(2) << time.tm_mday << " " << std::setw(2) << time.tm_hour << ":" << std::setw(2) << time.tm_min << ":" << std::setw(2) << time.tm_sec;

    return timeString.str();
}

int main()
{
    const std::chrono::high_resolution_clock::time_point & timePoint = std::chrono::high_resolution_clock::now();

    std::cout << Time_Point_String(timePoint);
    return 0;
}

但是在Visual Studio 2017中,我得到了一个编译器错误:

错误C2664'__time64_t std :: chrono :: system_clock :: to_time_t(const std :: chrono :: system_clock :: time_point&)noexcept':无法将参数1从'const std :: chrono :: steady_clock :: time_point'转换为'const std :: chrono :: system_clock :: time_point&'

因此,不可能再将high_resolution_clock::time_point转换为不同的time_point例如system_clock::time_point ,又不可能将high_resolution_clock::time_point直接转换为time_t吗?

我该如何处理这种情况? 可能吗(有些SO帖子说它们只是完全不同的时钟,转换没有意义)? 据我所知,该函数完成了Visual Studio 2013应用程序中的预期工作,它为high_resolution time_point提供了正确的本地时间。

这来自于以下事实: std::chrono::high_resolution_clock std::chrono::steady_clock std::chrono::system_clockstd::chrono::steady_clock的类型别名:

std::chrono::high_resolution_clock表示实现所提供的最小滴答周期的时钟。 它可能是std::chrono::steady_clock std::chrono::system_clockstd::chrono::steady_clock ,或者是第三个独立时钟。

这意味着std::chrono::high_resolution_clock::time_point可以是std::chrono::system_clock::time_point的类型别名,也可以是其他类型。 从您的问题中,您可以猜到它对MSVC2013有用,使您的代码有效,但对MSVC2017无效,这使您的代码无效。

结论是,以下代码可能以未指定的方式有效(或无效)(取决于编译器及其目标体系结构):

std::chrono::high_resolution_clock::time_point timePoint = /* something */;
std::chrono::system_clock::to_time_t(timePoint);

您只能在同一时钟的time_point之间time_point转换。 std::chrono::high_resolution_clock是另一个时钟的别名。 如果碰巧是std::chrono::system_clock则可以转换为time_t。

如果std::chrono::high_resolution_clock是另一个时钟,则可以通过将当前时间与std::chrono::high_resolution_clock的输入时间之间的差值加到上,将其近似转换为std::chrono::system_clock 。系统时间:

#include <iostream>
#include <chrono>

int main()
{
  auto input = std::chrono::high_resolution_clock::now();

  auto highResNow = std::chrono::high_resolution_clock::now();
  auto systemNow = std::chrono::system_clock::now();
  auto output = systemNow + (highResNow - input);
  std::cout << std::chrono::system_clock::to_time_t( output ) << "\n";
}

请注意,转换只是近似,理想highResNowsystemNow需要在同一时间来计算的,但会有他们之间小的差距。 输入时间和当前时间相隔越远,转换也将越不可靠。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM