kiba-engine
timer.c
1 #include <kiba/platform/timer.h>
2 
3 // TODO this is scuffed and should be rethought
4 #define __USE_POSIX199309
5 #include <time.h>
6 
7 timestamp time_now(void) {
8  struct timespec ts;
9  clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
10  return (timestamp){
11  .s = ts.tv_sec,
12  .ns = ts.tv_nsec,
13  };
14 }
15 
16 static inline struct timespec time_diff_internal(timestamp start, timestamp end) {
17  struct timespec diff;
18  if ((end.ns - start.ns) < 0) {
19  diff.tv_sec = end.s - start.s - 1;
20  diff.tv_nsec = 1000000000 + end.ns - start.ns;
21  } else {
22  diff.tv_sec = end.s - start.s;
23  diff.tv_nsec = end.ns - start.ns;
24  }
25  return diff;
26 }
27 
28 f64 time_diff_s(timestamp start, timestamp end) {
29  struct timespec diff = time_diff_internal(start, end);
30  return (f64) diff.tv_sec + (f64) diff.tv_nsec * 0.000000001;
31 }
32 
33 f64 time_diff_ms(timestamp start, timestamp end) {
34  struct timespec diff = time_diff_internal(start, end);
35  return (f64) diff.tv_sec * 1000.0 + (f64) diff.tv_nsec * 0.000001;
36 }
Definition: timer.h:5