Skip to content

Instantly share code, notes, and snippets.

@nanokatze
Created October 1, 2022 00:22
Show Gist options
  • Save nanokatze/ca3deac989ff813ee31a7f1ca331dc52 to your computer and use it in GitHub Desktop.
Save nanokatze/ca3deac989ff813ee31a7f1ca331dc52 to your computer and use it in GitHub Desktop.
/*
$ cc -O1 tsc_lol.c
$ ./a.out
1187.867 ms
11.879 ns per clock_gettime CLOCK_MONOTONIC
*/
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdint.h>
#include <time.h>
static int64_t
timespec_diff(struct timespec a, struct timespec b)
{
return (int64_t)(a.tv_sec - b.tv_sec) * 1000000000 + (int64_t)a.tv_nsec - (int64_t)b.tv_nsec;
}
int main(void) {
int n = 100000000;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int i = 0; i < n; i++) {
struct timespec tmp;
clock_gettime(CLOCK_MONOTONIC, &tmp);
}
clock_gettime(CLOCK_MONOTONIC, &t1);
fprintf(stderr, "%.3f ms\n", (double)timespec_diff(t1, t0) / 1e6);
fprintf(stderr, "%.3f ns per clock_gettime CLOCK_MONOTONIC\n", (double)timespec_diff(t1, t0) / n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment