在 Linux 中获取自纪元以来的秒数

新手上路,请多包涵

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

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

但是如何上 Linux 呢?

原文由 Boris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 344
1 个回答

您已经在使用它: std::time(0) (不要忘记 #include <ctime> )。但是, std::time 实际上是否返回标准中未指定纪元以来的时间( C11 ,由 C++ 标准引用):

7.27.2.4 time 函数

概要

> #include <time.h>
> time_t time(time_t *timer);
>
> ```
>
> ### 描述
>
> time 函数确定当前的日历时间。 _**该值的编码未指定。**_ \[强调我的\]

对于 C++,C++11 及更高版本提供 [`time_since_epoch`](http://en.cppreference.com/w/cpp/chrono/time_point/time_since_epoch) 。然而,在 C++20 之前, [`std::chrono::system_clock`](https://en.cppreference.com/w/cpp/chrono/system_clock) 的时代是未指定的,因此在以前的标准中可能是不可移植的。

尽管如此,在 Linux 上, `std::chrono::system_clock` 通常即使在 C++11、C++14 和 C++17 中也会使用 Unix 时间,因此您可以使用以下代码:

#include

// 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();

}

”`

原文由 Zeta 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题