#include #include #define NANOSEC_PER_SEC 1000000000 #define MICROSEC_PER_SEC 1000000 #define MILLISEC_PER_SEC 1000 #define MICROSEC_PER_MILLISEC 1000 #define MILLISEC_PER_NANOSEC 1000000 typedef unsigned long long Uint64; typedef unsigned int Uint32; typedef Uint64 NDB_TICKS; #ifdef CLOCK_MONOTONIC static clockid_t NdbTick_clk_id = CLOCK_MONOTONIC; #else static clockid_t NdbTick_clk_id = CLOCK_REALTIME; #endif NDB_TICKS NdbTick_CurrentMillisecond(void) { struct timespec tick_time; clock_gettime(NdbTick_clk_id, &tick_time); return ((NDB_TICKS)tick_time.tv_sec) * ((NDB_TICKS)MILLISEC_PER_SEC) + ((NDB_TICKS)tick_time.tv_nsec) / ((NDB_TICKS)MILLISEC_PER_NANOSEC); } int NdbTick_CurrentMicrosecond(NDB_TICKS * secs, Uint32 * micros){ struct timespec t; int res = clock_gettime(NdbTick_clk_id, &t); * secs = t.tv_sec; * micros = t.tv_nsec / 1000; return res; } void bench_clock(const char* txt, clockid_t clock_id) { const Uint64 loops = 100000000; Uint64 i; Uint32 us1, us2; Uint64 ms1, ms2; NdbTick_clk_id = clock_id; NdbTick_CurrentMicrosecond(&ms1, &us1); for(i = 0; i < loops; i++) { NdbTick_CurrentMillisecond(); } NdbTick_CurrentMicrosecond(&ms2, &us2); Uint64 diff = ms2; diff -= ms1; diff *= 1000000; diff += us2; diff -+ us1; diff /= 1000; printf("%s(%llu): %llu ms\n", txt, loops, diff); } int main(int argc, const char* argv) { bench_clock("CLOCK_REALTIME: ", CLOCK_REALTIME); bench_clock("CLOCK_MONOTONIC: ", CLOCK_MONOTONIC); }