1 #include <inttypes.h> 2 #include <sys/types.h> 3 #include <time.h> 4 #include <unistd.h> 5 6 #define noinline __attribute__((__noinline__)) 7 GetSystemClock()8static inline uint64_t GetSystemClock() { 9 timespec ts; 10 // Assume clock_gettime() doesn't fail. 11 clock_gettime(CLOCK_MONOTONIC, &ts); 12 return ts.tv_sec * 1000000000ULL + ts.tv_nsec; 13 } 14 15 constexpr int LOOP_COUNT = 100000000; RunFunction()16uint64_t noinline RunFunction() { 17 uint64_t start_time_in_ns = GetSystemClock(); 18 for (volatile int i = 0; i < LOOP_COUNT; ++i) { 19 } 20 return GetSystemClock() - start_time_in_ns; 21 } 22 SleepFunction(unsigned long long sleep_time_in_ns)23uint64_t noinline SleepFunction(unsigned long long sleep_time_in_ns) { 24 uint64_t start_time_in_ns = GetSystemClock(); 25 struct timespec req; 26 req.tv_sec = sleep_time_in_ns / 1000000000; 27 req.tv_nsec = sleep_time_in_ns % 1000000000; 28 nanosleep(&req, nullptr); 29 return GetSystemClock() - start_time_in_ns; 30 } 31 GlobalFunction()32void noinline GlobalFunction() { 33 uint64_t total_sleep_time_in_ns = 0; 34 uint64_t total_run_time_in_ns = 0; 35 while (true) { 36 total_run_time_in_ns += RunFunction(); 37 if (total_sleep_time_in_ns < total_run_time_in_ns) { 38 total_sleep_time_in_ns += SleepFunction(total_run_time_in_ns - total_sleep_time_in_ns); 39 } 40 } 41 } 42 main()43int main() { 44 GlobalFunction(); 45 return 0; 46 } 47