Skip to content

Instantly share code, notes, and snippets.

@nanokatze
Last active August 7, 2019 12:51
Show Gist options
  • Save nanokatze/5ef63563bef34a8354d1b15be738225d to your computer and use it in GitHub Desktop.
Save nanokatze/5ef63563bef34a8354d1b15be738225d to your computer and use it in GitHub Desktop.
#define _POSIX_C_SOURCE 200809L
#include <stdatomic.h>
#include <stddef.h>
#include <stdio.h>
/*
#include <windows.h>
*/
#include <pthread.h>
#include <time.h>
static atomic_size_t ticks = 0;
static void *
timer(void *a)
{
size_t t = 0;
/* do not use -funroll-all-loops */
for (;;) {
atomic_store_explicit(&ticks, t, memory_order_release);
t++;
atomic_store_explicit(&ticks, t, memory_order_release);
t++;
atomic_store_explicit(&ticks, t, memory_order_release);
t++;
atomic_store_explicit(&ticks, t, memory_order_release);
t++;
}
}
int
main(void)
{
pthread_t timer_pid;
pthread_create(&timer_pid, NULL, timer, NULL);
/*
DWORD timer_pid;
CreateThread(NULL, 0, timer, NULL, 0, &timer_pid);
*/
struct timespec old_time;
clock_gettime(CLOCK_MONOTONIC, &old_time);
size_t old_tick = 0;
for (;;) {
size_t cur_tick = atomic_load_explicit(&ticks, memory_order_acquire);
if (cur_tick - old_tick < 10000) {
continue;
}
struct timespec cur_time;
clock_gettime(CLOCK_MONOTONIC, &cur_time);
double elapsed = (double) (cur_time.tv_sec - old_time.tv_sec)
+ (cur_time.tv_nsec / 1e9 - old_time.tv_nsec / 1e9);
double time_unit = elapsed / (cur_tick - old_tick);
printf("one tick = %.12f seconds\n", time_unit);
old_time = cur_time;
old_tick = cur_tick;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment