Skip to content

Instantly share code, notes, and snippets.

@wwalker
Last active July 25, 2021 17:38
Show Gist options
  • Save wwalker/aec7b3da7cce49fbb14106b05f9ec328 to your computer and use it in GitHub Desktop.
Save wwalker/aec7b3da7cce49fbb14106b05f9ec328 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
// from <sys/time.h>
// used timersub macro, changed timeval to timespec
// kept the order of operands the same, that is a - b = result
# define timespec_diff_macro(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
if ((result)->tv_nsec < 0) { \
--(result)->tv_sec; \
(result)->tv_nsec += 1000000000; \
} \
} while (0)
int main(int argc, char **argv)
{
struct timespec start, stop, delta;
struct timespec duration, remaining;
struct timezone tz;
int continuations = 0;
duration.tv_sec = 0;
duration.tv_nsec = 1000;
clock_gettime(CLOCK_MONOTONIC, &start);
for (int x = 0; x < 1000; x++) {
while ( nanosleep(&duration, &remaining) == -1) {
duration.tv_sec = remaining.tv_sec;
duration.tv_nsec = remaining.tv_nsec;
continuations++;
}
}
clock_gettime(CLOCK_MONOTONIC, &stop);
timespec_diff_macro(&stop, &start, &delta);
printf("%ld.%09ld\n", start.tv_sec, start.tv_nsec);
printf("%ld.%09ld\n", stop.tv_sec, stop.tv_nsec);
printf("%ld.%09ld\n", delta.tv_sec, delta.tv_nsec);
printf("%d\n", continuations);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment