Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Created August 7, 2023 10:32
Show Gist options
  • Save fabiolimace/f267bf60aa621f65c48b9c1ae790b701 to your computer and use it in GitHub Desktop.
Save fabiolimace/f267bf60aa621f65c48b9c1ae790b701 to your computer and use it in GitHub Desktop.
Measure the distance between milliseconds using div and milliseconds using shift
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
long get_milliseconds_using_div(void)
{
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
return ((tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L));
}
long get_milliseconds_using_shift(void)
{
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
return ((tp.tv_sec << 10) | (tp.tv_nsec >> 20));
}
void measure_distance()
{
long div = get_milliseconds_using_div();
long shift = get_milliseconds_using_shift();
printf("timestamp using div: %ld ms\n", div);
printf("timestamp using shift: %ld ms\n", shift);
printf("distance in seconds: %ld s\n", (shift - div) / 1000);
printf("distance in days: %ld days\n", (shift - div) / 1000 / 60 / 60 / 24);
}
int main()
{
measure_distance(); // measure the difference between timestamps TODAY
}
@fabiolimace
Copy link
Author

fabiolimace commented Aug 7, 2023

OUTPUT:

user@computer:~$ gcc -O0 measure_distance_get_milliseconds.c && ./a.out 
timestamp using div:   1691404335877 ms
timestamp using shift: 1731998039876 ms
distance in seconds:   40593703 s
distance in days:      469 days

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