#include #include #include #include #include #include #include static int64_t gtod(void) { struct timeval tv; int64_t now; gettimeofday(&tv, NULL); now = ((int64_t)tv.tv_sec) * 1000000; now += tv.tv_usec; return now; } static int64_t clk(void) { struct timespec tv; int64_t now; clock_gettime(CLOCK_MONOTONIC, &tv); now = ((int64_t)tv.tv_sec) * 1000000; now += (tv.tv_nsec / 1000); return now; } int main(int argc, char *argv[]) { struct timespec tv; int n, count = 10; int64_t expected = 100; int64_t (*time_get)() = gtod; int opt; while ((opt = getopt(argc, argv, "cs:n:")) != EOF) { switch (opt) { case 'c': time_get = clk; break; case 's': expected = atoi(optarg); break; case 'n': count = atoi(optarg); break; } } expected *= 1000; /* usec */ tv.tv_sec = 0; tv.tv_nsec = expected * 1000; for (n = 0; n < count; n++) { int64_t start = (*time_get)(); int64_t latency; int err = nanosleep(&tv, NULL); if (err) { perror("nanosleep"); break; } latency = (*time_get)() - start; printf("%08d latency %ld/%ld (%.4f%%)\n", n, latency, expected, 100 * (((float)latency - expected) / expected)); } return 0; }