Get seconds since epoch in Linux
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 The
time
functionSynopsis
#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]
For C++, C++11 and later provide time_since_epoch
. However, before C++20 the epoch of std::chrono::system_clock
was unspecified and therefore possibly non-portable in previous standards.
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();
}
In C.
time(NULL);
In C++.
std::time(0);
And the return value of time is : time_t not long long
The native Linux function for getting time is gettimeofday()
[there are some other flavours too], but that gets you the time in seconds and nanoseconds, which is more than you need, so I would suggest that you continue to use time()
. [Of course, time()
is implemented by calling gettimeofday()
somewhere down the line - but I don't see the benefit of having two different pieces of code that does exactly the same thing - and if you wanted that, you'd be using GetSystemTime()
or some such on Windows [not sure that's the right name, it's been a while since I programmed on Windows]