Attention: open in a new window. PDFPrint

What time is it, please?

Reading the current time since 01/01/1970 in milliseconds (or even microseconds) is something, most operating systems provide by system calls. One of the most unpleasent things about it is, that every operating system provides other methods (or at least method names) to read this value. This is not really a problem, if you use higher level languages like Java or something like this, but if you try to develop portable applications using C/C++ you might dislike this.

In this case it might be good to find someone out there providing a little code snipped that allows reading the system time in a more generic way. So here is my little code snipped:

#ifdef __unix__
#include <sys/time.h>
#include <stdint.h>

/**
* Gets the current system time in seconds as a double value.
*/
inline double getCurrentTime() {
timeval tv;
gettimeofday(&tv, 0);
uint64_t uitv = tv.tv_sec;
uitv *= 1000000;
uitv += tv.tv_usec;

return uitv / 1000000.0;
}

#endif

#ifdef _WIN32
#include <windows.h>

/**
* Gets the current system time in seconds as a double value.
*/
inline double getCurrentTime() {
FILETIME filetime;
GetSystemTimeAsFileTime(&filetime);
UINT64 rc = filetime.dwHighDateTime;
rc <<= sizeof(filetime.dwLowDateTime);
rc += filetime.dwLowDateTime;
return rc / 10000000.0;
}

#endif

This should work for windows as well as unix mashines. I do not know, how MacOS provides the system time. The unix-code might work on those machines as well, but I am not able to test this.

The method returns the current time since January, 1st 1970 in seconds. You will find milli- or microseconds behind the decimal point of the double. If you do not like to cope with double values you might change the methods on your needs. The double-values are very useful, if you are working with OpenGL and like to animate the stuff you draw.