-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.h
More file actions
42 lines (32 loc) · 851 Bytes
/
timer.h
File metadata and controls
42 lines (32 loc) · 851 Bytes
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
#ifndef TIMEOUT_H
#define TIMEOUT_H
#include <time.h>
#include <math.h>
#include <stdint.h>
#define UNIT_TO_NANO(value) ((value)*1000000000)
#define UNIT_TO_MICRO(value) ((value)*1000000)
typedef struct timespec Timer;
static inline int timer_start(Timer *self)
{
return clock_gettime(CLOCK_MONOTONIC, self);
}
/*Timeout in seconds*/
static inline bool timeout_elapsed(Timer *reference, uint32_t timeout)
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (now.tv_sec - reference->tv_sec) > timeout;
}
static inline void timer_sleep(float seconds)
{
struct timespec req;
struct timespec rem;
int rv;
req.tv_sec = trunc(seconds);
req.tv_nsec = UNIT_TO_NANO(seconds - req.tv_sec);
do{
rv = nanosleep(&req, &rem);
req = rem;
}while(rv != 0);
}
#endif /* TIMEOUT_H */