【问题标题】:how can I set system time from system_clock::time_point如何从 system_clock::time_point 设置系统时间
【发布时间】:2013-05-07 22:02:29
【问题描述】:

如何从 std::chrono::system_clock::time_point 设置平台(windows、linux、android)的系统时间。

【问题讨论】:

  • Erm.. 没有chrono::system_time。有system_clock,但那是不同的。 chrono 是关于时间设施,而不是日期时间设施。
  • 我是对的...我的意思是 system_clock。

标签: c++ c++11


【解决方案1】:

您不能使用 std::chrono 工具来设置任何时钟的时间。您可以做的最好的事情是制造一个std::chrono::system_clock::time_point 来表示所选时间,将其转换为time_t,然后将其与您平台的API 一起使用来设置时钟。

【讨论】:

  • 所以对于 Windows,我必须从 time_point 转换为 time_t,从 time_t 转换为 tm,从 tm 转换为 SYSTEMTIME。在 unix 环境中,哪个函数设置系统时间(UTC)?
  • clock_settime 和/或 settimeofday 取决于平台。
  • 将其转换为time_t 很奇怪;这会失去亚秒级的精度,而且我不知道任何平台设置时钟的 API 直接根据该类型。而是直接从time_point 转到您系统的相关类型。
【解决方案2】:

对于 Linux,我喜欢来自 Converting between timespec & std::chrono 的参考代码:

#include <time.h>
#include <chrono>

using std::chrono; // for example brevity

constexpr timespec timepointToTimespec(
    time_point<system_clock, nanoseconds> tp)
{
    auto secs = time_point_cast<seconds>(tp);
    auto ns = time_point_cast<nanoseconds>(tp) -
             time_point_cast<nanoseconds>(secs);

    return timespec{secs.time_since_epoch().count(), ns.count()};
}

const char* timePointToChar(
    const time_point<system_clock, nanoseconds>& tp) {
    time_t ttp = system_clock::to_time_t(tp);
    return ctime(&ttp);
}

const time_point system_time = system_clock::now();
cout << "System time = " << timePointToChar(system_time) << endl;

const timespec ts = timepointToTimespec(system_time);
clock_settime(CLOCK_REALTIME, &ts);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2015-02-06
    • 1970-01-01
    相关资源
    最近更新 更多