gcode-interpreter

A gcode interpreter I use to control lasers.
git clone git://git.christianermann.dev/gcode-interpreter
Log | Files | Refs | README | LICENSE

timing.c (1495B)


      1 #include "timing.h"
      2 
      3 #include <time.h>
      4 
      5 Time time_make(long time_s, long time_ns) {
      6     const long billion = 1000000000;
      7     long overflow = (time_ns >= 0 ? time_ns : time_ns - (billion - 1)) / billion;
      8     Time t = {
      9         .time_s = time_s + overflow,
     10         .time_ns = time_ns - overflow * billion,
     11     };
     12     return t;
     13 }
     14 
     15 Time time_zero() {
     16     return time_make(0, 0);
     17 };
     18 
     19 Time time_get() {
     20     struct timespec ts;
     21     clock_gettime(CLOCK_MONOTONIC, &ts);
     22     return time_make(ts.tv_sec, ts.tv_nsec);
     23 };
     24 
     25 Time time_add(const Time* t0, const Time* t1) {
     26     long time_s = t0->time_s + t1->time_s;
     27     long time_ns = t0->time_ns + t1->time_ns;
     28     return time_make(time_s, time_ns);
     29 }
     30 
     31 Time time_sub(const Time* t0, const Time* t1) {
     32     long time_s = t0->time_s - t1->time_s;
     33     long time_ns = t0->time_ns - t1->time_ns;
     34     return time_make(time_s, time_ns);
     35 }
     36 
     37 float time_div(const Time* t0, const Time* t1) {
     38     long denominator = t1->time_s * 1e9 + t1->time_ns;
     39     float q_a = ((float)t0->time_s / denominator) * 1e9;
     40     float q_b = (float)t0->time_ns / denominator;
     41     return q_a + q_b;
     42 }
     43 
     44 int time_cmp(const Time* t0, const Time* t1) {
     45     if (t0->time_s > t1->time_s) {
     46         return 1;
     47     }
     48     if (t0->time_s < t1->time_s) {
     49         return -1;
     50     }
     51     if (t0->time_ns > t1->time_ns) {
     52         return 1;
     53     }
     54     if (t0->time_ns < t1->time_ns) {
     55         return -1;
     56     }
     57     return 0;
     58 }
     59 
     60 bool time_eql_zero(const Time* t) {
     61     return t->time_s == 0 && t->time_ns == 0;
     62 }