Make cpputils::time::now() work on windows

This commit is contained in:
Sebastian Messmer 2018-05-17 06:37:47 -07:00
parent 9d872ea00c
commit a686129243

View File

@ -1,26 +1,54 @@
#include "time.h"
#if defined(__MACH__) && !defined(CLOCK_REALTIME)
#if defined(_MSC_VER)
// Windows
// Implementation taken from https://stackoverflow.com/a/31335254
// Implements clock_gettime for Mac OS X before 10.12 (where it is not implemented by in the standard library)
// Source: http://stackoverflow.com/a/9781275/829568
#include <Windows.h>
constexpr __int64 exp7 = 10000000i64; //1E+7
constexpr __int64 exp9 = 1000000000i64; //1E+9
constexpr __int64 w2ux = 116444736000000000i64; //1.jan1601 to 1.jan1970
namespace cpputils {
namespace time {
struct timespec now() {
__int64 wintime;
GetSystemTimeAsFileTime((FILETIME*)&wintime);
wintime -= w2ux;
struct timespec spec;
spec.tv_sec = wintime / exp7;
spec.tv_nsec = wintime % exp7 * 100;
return spec;
}
}
}
#elif defined(__MACH__) && !defined(CLOCK_REALTIME)
// OSX before 10.12 has no clock_gettime
// Implementation taken from: http://stackoverflow.com/a/9781275/829568
// Caution: The returned value is less precise than the returned value from a linux clock_gettime would be.
#include <sys/time.h>
#define CLOCK_REALTIME 0
namespace {
int clock_gettime(int /*clk_id*/, struct timespec *result) {
struct timeval now;
int rv = gettimeofday(&now, nullptr);
if (rv) {
return rv;
}
result->tv_sec = now.tv_sec;
result->tv_nsec = now.tv_usec * 1000;
return 0;
namespace cpputils {
namespace time {
struct timespec now() {
struct timeval now {};
int rv = gettimeofday(&now, nullptr);
if (rv) {
throw std::runtime_error("gettimeofday failed with " + std::to_string(rv));
}
struct timespec result;
result->tv_sec = now.tv_sec;
result->tv_nsec = now.tv_usec * 1000;
return now;
}
}
}
#endif
#else
// Linux or OSX with clock_gettime implementation
namespace cpputils {
namespace time {
@ -33,3 +61,5 @@ struct timespec now() {
}
}
#endif