-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtruesleep.c
More file actions
54 lines (44 loc) · 1.35 KB
/
truesleep.c
File metadata and controls
54 lines (44 loc) · 1.35 KB
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
#include <time.h>
#include <stdio.h>
/**
* Sleep for `sec' seconds, without relying on the wall clock of time(2)
* or gettimeofday(2).
*
* Under ideal conditions is accurate to one microsecond. To get nanosecond
* accuracy, replace sleep()/usleep() with something with higher resolution
* like nanosleep() or ppoll().
*/
void true_sleep(int sec) {
struct timespec ts_start;
struct timespec ts_end;
clock_gettime(CLOCK_MONOTONIC, &ts_start);
ts_end = ts_start;
ts_end.tv_sec += sec;
for (;;) {
struct timespec ts_current;
struct timespec ts_remaining;
clock_gettime(CLOCK_MONOTONIC, &ts_current);
ts_remaining.tv_sec = ts_end.tv_sec - ts_current.tv_sec;
ts_remaining.tv_nsec = ts_end.tv_nsec - ts_current.tv_nsec;
while (ts_remaining.tv_nsec > 1000000000) {
ts_remaining.tv_sec++;
ts_remaining.tv_nsec -= 1000000000;
}
while (ts_remaining.tv_nsec < 0) {
ts_remaining.tv_sec--;
ts_remaining.tv_nsec += 1000000000;
}
if (ts_remaining.tv_sec < 0) {
break;
}
if (ts_remaining.tv_sec > 0) {
sleep(ts_remaining.tv_sec);
} else {
usleep(ts_remaining.tv_nsec / 1000);
}
}
}
int main() {
true_sleep(10); // Sleep for 10 seconds
return 0;
}