Get seconds from the era on Linux

Is there a cross-platform solution for getting seconds from the era for Windows I use

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

But how to get into Linux?

+8
source share
3 answers

You already use it: std::time(0) (don't forget #include <ctime> ). However, does std::time really return time, since the epoch is not specified in the standard ( C11 , which the C ++ standard refers to):

7.27.2.4 time function

abstract

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

Description

The time function determines the current calendar time. The value encoding is not specified. [Emphasis mine]

For C ++, C ++ 11 and later time_since_epoch . However, only in C ++ 20 and later versions of std::chrono::system_clock was Unix Time set and it is undefined and therefore possibly std::chrono::system_clock in previous standards.

However, on Linux 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(); } 
+17
source

In C.

 time(NULL); 

In C ++.

 std::time(0); 

And the return value of time: time_t is not long

+14
source

Linux's native function for getting gettimeofday() [there are other flavors], but it gives you time in seconds and nanoseconds, which is more than you need, so I would advise you to continue to use time() . [Of course, time() is implemented by calling gettimeofday() somewhere down the line, but I don’t see the advantage of having two different pieces of code that do exactly the same thing - and if you wanted to, use GetSystemTime() or some of them on Windows [not sure if the name is correct, it was time since I programmed on Windows]

+2
source

All Articles