Skip to content

Instantly share code, notes, and snippets.

@gfx
Created April 27, 2023 13:05
Show Gist options
  • Save gfx/54b77923215e8aca565003ca089a8d96 to your computer and use it in GitHub Desktop.
Save gfx/54b77923215e8aca565003ca089a8d96 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#define NUM_ITERATIONS 1000000
uint64_t timespec_to_ns(struct timespec ts) {
return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}
uint64_t measure_overhead(clockid_t clock_type) {
struct timespec start, x, end;
uint64_t start_ns, end_ns, total_ns = 0;
clock_gettime(CLOCK_MONOTONIC_COARSE, &start);
for (int i = 0; i < NUM_ITERATIONS; i++) {
clock_gettime(clock_type, &x);
}
clock_gettime(CLOCK_MONOTONIC_COARSE, &end);
start_ns = timespec_to_ns(start);
end_ns = timespec_to_ns(end);
total_ns += (end_ns - start_ns);
return total_ns / NUM_ITERATIONS;
}
int main() {
uint64_t thread_cputime_id_overhead = measure_overhead(CLOCK_THREAD_CPUTIME_ID);
uint64_t monotonic_overhead = measure_overhead(CLOCK_MONOTONIC);
uint64_t monotonic_coarse_overhead = measure_overhead(CLOCK_MONOTONIC_COARSE);
printf("CLOCK_THREAD_CPUTIME_ID overhead: %lu ns\n", thread_cputime_id_overhead);
printf("CLOCK_MONOTONIC overhead: %lu ns\n", monotonic_overhead);
printf("CLOCK_MONOTONIC_COARSE overhead: %lu ns\n", monotonic_coarse_overhead);
return 0;
}
@gfx
Copy link
Author

gfx commented Apr 27, 2023

In my Linux machine (NUC 10, Ubuntu 22.04), a typical output is something like this:

CLOCK_THREAD_CPUTIME_ID overhead: 192 ns
CLOCK_MONOTONIC overhead: 16 ns
CLOCK_MONOTONIC_COARSE overhead: 4 ns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment