Unify the time handling
[fio.git] / time.c
CommitLineData
3c39a379
JA
1#include <time.h>
2#include <sys/time.h>
3
4#include "fio.h"
5
263e529f 6static struct timeval genesis;
fd841467 7static unsigned long ns_granularity;
263e529f 8
3c39a379
JA
9/*
10 * busy looping version for the last few usec
11 */
6dd6f2cd 12void usec_spin(unsigned int usec)
3c39a379
JA
13{
14 struct timeval start;
15
02bcaa8c 16 fio_gettime(&start, NULL);
3c39a379
JA
17 while (utime_since_now(&start) < usec)
18 nop;
19}
20
21void usec_sleep(struct thread_data *td, unsigned long usec)
22{
fd841467
JA
23 struct timespec req;
24 struct timeval tv;
3c39a379
JA
25
26 do {
fd841467
JA
27 unsigned long ts = usec;
28
29 if (usec < ns_granularity) {
6dd6f2cd 30 usec_spin(usec);
3c39a379
JA
31 break;
32 }
33
fd841467 34 ts = usec - ns_granularity;
3c39a379 35
fd841467
JA
36 if (ts >= 1000000) {
37 req.tv_sec = ts / 1000000;
38 ts -= 1000000 * req.tv_sec;
39 } else
40 req.tv_sec = 0;
41
42 req.tv_nsec = ts * 1000;
43 fio_gettime(&tv, NULL);
44
45 if (nanosleep(&req, NULL) < 0)
3c39a379
JA
46 break;
47
fd841467
JA
48 ts = utime_since_now(&tv);
49 if (ts >= usec)
50 break;
3c39a379 51
fd841467 52 usec -= ts;
3c39a379
JA
53 } while (!td->terminate);
54}
55
aa60bc58 56uint64_t mtime_since_genesis(void)
263e529f
JA
57{
58 return mtime_since_now(&genesis);
59}
60
0de5b26f
JA
61uint64_t utime_since_genesis(void)
62{
63 return utime_since_now(&genesis);
64}
65
b29ee5b3
JA
66int in_ramp_time(struct thread_data *td)
67{
68 return td->o.ramp_time && !td->ramp_time_over;
69}
70
721938ae
JA
71int ramp_time_over(struct thread_data *td)
72{
73 struct timeval tv;
74
75 if (!td->o.ramp_time || td->ramp_time_over)
76 return 1;
77
78 fio_gettime(&tv, NULL);
0de5b26f 79 if (utime_since(&td->epoch, &tv) >= td->o.ramp_time) {
721938ae 80 td->ramp_time_over = 1;
b29ee5b3
JA
81 reset_all_stats(td);
82 td_set_runstate(td, TD_RAMP);
721938ae
JA
83 return 1;
84 }
85
86 return 0;
87}
88
03e20d68 89void fio_time_init(void)
263e529f 90{
fd841467
JA
91 int i;
92
c223da83
JA
93 fio_clock_init();
94
fd841467
JA
95 /*
96 * Check the granularity of the nanosleep function
97 */
98 for (i = 0; i < 10; i++) {
99 struct timeval tv;
100 struct timespec ts;
101 unsigned long elapsed;
102
103 fio_gettime(&tv, NULL);
104 ts.tv_sec = 0;
105 ts.tv_nsec = 1000;
106
107 nanosleep(&ts, NULL);
108 elapsed = utime_since_now(&tv);
109
110 if (elapsed > ns_granularity)
111 ns_granularity = elapsed;
112 }
263e529f 113}
6043c579 114
a2f77c9f
JA
115void set_genesis_time(void)
116{
117 fio_gettime(&genesis, NULL);
118}
119
6043c579
JA
120void fill_start_time(struct timeval *t)
121{
122 memcpy(t, &genesis, sizeof(genesis));
123}