自Linux时代以来获得秒数 [英] Get seconds since epoch in Linux
问题描述
对于我使用的Windows,是否存在跨平台解决方案以获取自时代以来的秒数
Is there cross-platform solution to get seconds since epoch, for windows i use
long long NativesGetTimeInSeconds()
{
return time (NULL);
}
但是如何在Linux上运行?
But how to get on Linux?
推荐答案
您已经在使用它: #include< ctime>
).但是, std :: time
是否实际返回时间,因为标准中未指定纪元(
You're already using it: std::time(0)
(don't forget to #include <ctime>
). However, whether std::time
actually returns the time since epoch isn't specified in the standard (C11, referenced by the C++ standard):
7.27.2.4
time
函数简介
#include <time.h>
time_t time(time_t *timer);
说明
时间功能确定当前日历时间. 值的编码未指定. [强调我的]
Description
The time function determines the current calendar time. The encoding of the value is unspecified. [emphasis mine]
对于C ++,C ++ 11和更高版本提供 time_since_epoch 代码>
.但是,仅在C ++ 20和更高版本中, std :: chrono的纪元::system_clock
被指定为Unix Time,并且未指定,因此在以前的标准中可能不可移植.
For C++, C++11 and later provide time_since_epoch
. However, only in C++20 and later the epoch of std::chrono::system_clock
was specified to be Unix Time, and it is unspecified and therefore possibly non-portable in previous standards.
仍然,在Linux上,即使在C ++ 11,C ++ 14和C ++ 17中, std :: chrono :: system_clock
通常也将使用Unix Time,因此您可以使用以下代码代码:
Still, on Linux the std::chrono::system_clock
will usually use Unix Time even in C++11, C++14 and C++17, so you can use the following code:
#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();
}
这篇关于自Linux时代以来获得秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!