Make cpputils::time::now() work on windows
This commit is contained in:
parent
9d872ea00c
commit
a686129243
@ -1,26 +1,54 @@
|
|||||||
#include "time.h"
|
#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)
|
#include <Windows.h>
|
||||||
// Source: http://stackoverflow.com/a/9781275/829568
|
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.
|
// Caution: The returned value is less precise than the returned value from a linux clock_gettime would be.
|
||||||
|
|
||||||
#include <sys/time.h>
|
#include <sys/time.h>
|
||||||
#define CLOCK_REALTIME 0
|
namespace cpputils {
|
||||||
namespace {
|
namespace time {
|
||||||
int clock_gettime(int /*clk_id*/, struct timespec *result) {
|
|
||||||
struct timeval now;
|
struct timespec now() {
|
||||||
|
struct timeval now {};
|
||||||
int rv = gettimeofday(&now, nullptr);
|
int rv = gettimeofday(&now, nullptr);
|
||||||
if (rv) {
|
if (rv) {
|
||||||
return rv;
|
throw std::runtime_error("gettimeofday failed with " + std::to_string(rv));
|
||||||
}
|
}
|
||||||
|
struct timespec result;
|
||||||
result->tv_sec = now.tv_sec;
|
result->tv_sec = now.tv_sec;
|
||||||
result->tv_nsec = now.tv_usec * 1000;
|
result->tv_nsec = now.tv_usec * 1000;
|
||||||
return 0;
|
return now;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#else
|
||||||
|
// Linux or OSX with clock_gettime implementation
|
||||||
|
|
||||||
namespace cpputils {
|
namespace cpputils {
|
||||||
namespace time {
|
namespace time {
|
||||||
@ -33,3 +61,5 @@ struct timespec now() {
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#endif
|
Loading…
Reference in New Issue
Block a user