Last active
December 27, 2015 19:19
-
-
Save markpapadakis/7376127 to your computer and use it in GitHub Desktop.
Timings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// use e.g Timings::Minutes::Sleep(2), Timings::Seconds::ToMicroseconds(1) etc | |
#include <stdint.h> | |
#include <time.h> | |
#include <errno.h> | |
#include <switch.h> | |
namespace Timings | |
{ | |
template<uint64_t asNanoseconds> | |
struct Unit | |
{ | |
static inline uint64_t ToSeconds(const uint64_t n) | |
{ | |
return n * asNanoseconds / 1000000000ULL; | |
} | |
static inline uint64_t ToMinutes(const uint64_t n) | |
{ | |
return ToSeconds(n) / 60; | |
} | |
static inline uint64_t ToHours(const uint64_t n) | |
{ | |
return ToMinutes(n) / 60; | |
} | |
static inline uint64_t ToDays(const uint64_t n) | |
{ | |
return ToHours(n) / 24; | |
} | |
static inline uint64_t ToMicros(const uint64_t n) | |
{ | |
return n * asNanoseconds / 1000; | |
} | |
static inline uint64_t ToMillis(const uint64_t n) | |
{ | |
return n * asNanoseconds / 1000000; | |
} | |
static inline uint64_t ToNanos(const uint64_t n) | |
{ | |
return n * asNanoseconds; | |
} | |
static void Sleep(const uint64_t n) | |
{ | |
struct timespec req, rem; | |
req.tv_sec = ToSeconds(n); | |
req.tv_nsec= (n * asNanoseconds) - (req.tv_sec * 1000000000); | |
while (nanosleep(&req, &rem) == -1 && errno == EINTR) | |
req = rem; | |
} | |
}; | |
struct Seconds | |
: public Unit<1000000000ULL> | |
{ | |
}; | |
struct Milliseconds | |
: public Unit<1000000UL> | |
{ | |
}; | |
struct Nanoseconds | |
: public Unit<1> | |
{ | |
}; | |
struct Minutes | |
: public Unit<1000000000ULL * 60> | |
{ | |
}; | |
struct Hours | |
: public Unit<1000000000ULL * 60 * 60> | |
{ | |
}; | |
struct Days | |
: public Unit<1000000000ULL * 60 * 60 * 24> | |
{ | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment