forked from cunha/dstructs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timespec.c
97 lines (87 loc) · 2.4 KB
/
timespec.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <assert.h>
#include <inttypes.h>
int timespec_cmp(struct timespec a, struct timespec b) /* {{{ */
{
return 2*((a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec)) +
(a.tv_nsec > b.tv_nsec) - (a.tv_nsec < b.tv_nsec);
} /* }}} */
int timespec_is_zero(struct timespec a) /* {{{ */
{
return (a.tv_sec == 0) && (a.tv_nsec == 0);
} /* }}} */
void timespec_fromdouble(double interval, struct timespec *ts) /* {{{ */
{
uint64_t nsec = ((uint64_t)(interval*1000000000)) % 1000000000;
ts->tv_sec = (time_t)interval;
ts->tv_nsec = (long)nsec;
} /* }}} */
double timespec_todouble(struct timespec ts) /* {{{ */
{
return ts.tv_sec + ts.tv_nsec / 1000000000.0;
} /* }}} */
void timespec_add(struct timespec a, struct timespec b, /* {{{ */
struct timespec *res)
{
res->tv_nsec = a.tv_nsec + b.tv_nsec;
res->tv_sec = a.tv_sec + b.tv_sec;
if(res->tv_nsec >= 1000000000) {
res->tv_sec++;
res->tv_nsec = res->tv_nsec % 1000000000;
}
} /* }}} */
void timespec_mult(struct timespec a, unsigned times, /* {{{ */
struct timespec *res)
{
uint64_t nano = a.tv_nsec * times;
res->tv_sec = a.tv_sec * times;
res->tv_sec += nano/1000000000;
res->tv_nsec = nano % 1000000000;
} /* }}} */
void timespec_sub(struct timespec a, struct timespec b, /* {{{ */
struct timespec *res)
{
if(timespec_cmp(a, b) < 0) {
res->tv_sec = 0;
res->tv_nsec = 0;
#ifndef NDEBUG
fprintf(stderr, "%s:%d error: %lu.%09ld - %lu.%09ld\n",
__FILE__, __LINE__,
a.tv_sec, a.tv_nsec, b.tv_sec, b.tv_nsec);
#endif
} else {
res->tv_nsec = a.tv_nsec - b.tv_nsec;
res->tv_sec = a.tv_sec - b.tv_sec;
if(res->tv_nsec < 0) {
res->tv_nsec += 1000000000;
res->tv_sec--;
}
}
} /* }}} */
double timespec_sub_double(struct timespec a, struct timespec b) /* {{{ */
{
return a.tv_sec - b.tv_sec +
(a.tv_nsec - b.tv_nsec)/1000000000.0;
} /* }}} */
char * timespec_str(struct timespec a) {/*{{{*/
char *buf = malloc(64);
assert(buf);
snprintf(buf, 64, "%lu.%09ld", a.tv_sec, a.tv_nsec);
return buf;
}/*}}}*/
void timespec_shift(struct timespec base, double fraction, /* {{{ */
struct timespec *target)
{
struct timespec ts;
double shift = base.tv_sec * fraction;
shift += (base.tv_nsec * fraction) / 1000000000.0;
timespec_fromdouble(fabs(shift), &ts);
if(fraction >= 0) {
timespec_add(*target, ts, target);
} else {
timespec_sub(*target, ts, target);
}
} /* }}} */