【问题标题】:Get seconds since epoch in Linux在 Linux 中获取自纪元以来的秒数
【发布时间】:2012-12-11 13:20:19
【问题描述】:

对于我使用的 Windows,是否有跨平台解决方案来获得自纪元以来的秒数

long long NativesGetTimeInSeconds()
{
    return time (NULL);
}

但是如何上 Linux 呢?

【问题讨论】:

标签: c++ linux windows time


【解决方案1】:

您已经在使用它:std::time(0)(别忘了#include <ctime>)。但是,std::time 是否实际上返回自 epoch 以来的时间并没有在标准中指定(C11,由 C++ 标准引用):

7.27.2.4 time 函数

概要

#include <time.h>
time_t time(time_t *timer);

说明

时间函数确定当前日历时间。 未指定值的编码。 [强调我的]

对于 C++,C++11 及更高版本提供time_since_epoch。然而,在 C++20 之前,std::chrono::system_clock 的时代是未指定的,因此在以前的标准中可能是不可移植的。

不过,在 Linux 上,std::chrono::system_clock 即使在 C++11、C++14 和 C++17 中通常也会使用 Unix Time,因此您可以使用以下代码:

#include <chrono>

// make the decltype slightly easier to the eye
using seconds_t = std::chrono::seconds;

// return the same type as seconds.count() below does.
// note: C++14 makes this a lot easier.
decltype(seconds_t().count()) get_seconds_since_epoch()
{
    // get the current time
    const auto now     = std::chrono::system_clock::now();

    // transform the time into a duration since the epoch
    const auto epoch   = now.time_since_epoch();

    // cast the duration into seconds
    const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(epoch);
    
    // return the number of seconds
    return seconds.count();
}

【讨论】:

  • 这不能保证给你自纪元以来的时间。文档只是说这是“通常”的情况。不便携。
  • 为了澄清,几年后:从 C++20 开始,std::chrono::system_clock(后一种方法演示)现在由标准保证为基于 Unix 纪元。
  • @JaminGrey 感谢您的提醒。我添加了一个关于 C++20 的注释。
【解决方案2】:

在 C 中。

time(NULL);

在 C++ 中。

std::time(0);

而时间的返回值是:time_t不是long long

【讨论】:

    【解决方案3】:

    获取时间的原生Linux函数是gettimeofday() [还有一些其他的口味],但它以秒和纳秒为单位获取时间,这超出了你的需要,所以我建议你继续使用time()。 [当然,time() 是通过调用gettimeofday() 来实现的——但我看不出拥有两段完全相同的代码的好处——如果你想要,你会在 Windows 上使用 GetSystemTime() 或类似名称[不确定这是正确的名称,我已经有一段时间没有在 Windows 上编程了]

    【讨论】:

    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 2019-12-04
    • 2020-02-11
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    相关资源
    最近更新 更多