timesynk/test/timer.c

65 lines
1.7 KiB
C

#include "timer.h"
void ftoi(float f, int p, long *i, long *d) {
long prec = 1;
int x = p;
while(x>0) {
prec *= 10;
x--;
}
*d = (long)((f - (long)f) * prec);
*i = (long)f;
}
void getTime(struct PTimer *time) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
time->s = ts.tv_sec;
time->m = ts.tv_sec*1000;
time->n = ts.tv_nsec;
}
void doSleep(long seconds, long milliseconds, long nanoseconds) {
struct timespec ts;
ts.tv_sec = seconds;
ts.tv_nsec = nanoseconds + (milliseconds*1000000);
if (nanosleep(&ts, NULL) < 0)
printf("ERR\n");
}
int main() {
printf(" - testing high precision timer - use Ctrl-C to quit\n");
struct PTimer start_timer;
getTime(&start_timer);
struct PTimer last_timer;
getTime(&last_timer);
printf("yup\n");
printf("\tstart PTimer values - s: %d, m: %d, n: %d\n", start_timer.s, start_timer.m, start_timer.n);
float tickrate = 1000.0f/60.0f; // 60 fps = 16.6666667ms
printf("\tstart tickrate: %f\n", tickrate);
struct PTimer sleep_time;
ftoi(tickrate, 6, &sleep_time.m, &sleep_time.n);
printf("\tstart tickrate: %ld.%ld\n", sleep_time.m, sleep_time.n);
sleep(2);
while(1) {
struct PTimer current_timer;
getTime(&current_timer);
// processing would occur here
struct PTimer delta_time;
delta_time.s = current_timer.s - last_timer.s;
delta_time.m = current_timer.m - last_timer.m;
delta_time.n = current_timer.n - last_timer.n;
printf("delta is %ds or %dm, with %dn (%d.%d)\n", delta_time.s, delta_time.m, delta_time.n, delta_time.m, delta_time.n);
printf("sleeping for %d.%dms\n", sleep_time.m, sleep_time.n);
last_timer = current_timer;
doSleep(0, sleep_time.m, sleep_time.n);
}
}