6 static struct timeval genesis;
7 static unsigned long ns_granularity;
9 unsigned long long utime_since(struct timeval *s, struct timeval *e)
12 unsigned long long ret;
14 sec = e->tv_sec - s->tv_sec;
15 usec = e->tv_usec - s->tv_usec;
16 if (sec > 0 && usec < 0) {
22 * time warp bug on some kernels?
24 if (sec < 0 || (sec == 0 && usec < 0))
27 ret = sec * 1000000ULL + usec;
32 unsigned long long utime_since_now(struct timeval *s)
36 fio_gettime(&t, NULL);
37 return utime_since(s, &t);
40 unsigned long mtime_since(struct timeval *s, struct timeval *e)
44 sec = e->tv_sec - s->tv_sec;
45 usec = e->tv_usec - s->tv_usec;
46 if (sec > 0 && usec < 0) {
56 * time warp bug on some kernels?
64 unsigned long mtime_since_now(struct timeval *s)
67 void *p = __builtin_return_address(0);
70 return mtime_since(s, &t);
73 unsigned long time_since_now(struct timeval *s)
75 return mtime_since_now(s) / 1000;
79 * busy looping version for the last few usec
81 void __usec_sleep(unsigned int usec)
85 fio_gettime(&start, NULL);
86 while (utime_since_now(&start) < usec)
90 void usec_sleep(struct thread_data *td, unsigned long usec)
96 unsigned long ts = usec;
98 if (usec < ns_granularity) {
103 ts = usec - ns_granularity;
106 req.tv_sec = ts / 1000000;
107 ts -= 1000000 * req.tv_sec;
111 req.tv_nsec = ts * 1000;
112 fio_gettime(&tv, NULL);
114 if (nanosleep(&req, NULL) < 0)
117 ts = utime_since_now(&tv);
122 } while (!td->terminate);
125 void rate_throttle(struct thread_data *td, unsigned long time_spent,
128 unsigned long usec_cycle;
131 if (!td->o.rate && !td->o.rate_iops)
135 bs = td->o.rw_min_bs;
136 else if (td_read(td))
137 bs = td->o.min_bs[DDIR_READ];
139 bs = td->o.min_bs[DDIR_WRITE];
141 usec_cycle = td->rate_usec_cycle * (bytes / bs);
143 if (time_spent < usec_cycle) {
144 unsigned long s = usec_cycle - time_spent;
146 td->rate_pending_usleep += s;
148 if (td->rate_pending_usleep >= 100000) {
151 fio_gettime(&t, NULL);
152 usec_sleep(td, td->rate_pending_usleep);
153 td->rate_pending_usleep -= utime_since_now(&t);
156 long overtime = time_spent - usec_cycle;
158 td->rate_pending_usleep -= overtime;
162 unsigned long mtime_since_genesis(void)
164 return mtime_since_now(&genesis);
167 static void fio_init time_init(void)
172 * Check the granularity of the nanosleep function
174 for (i = 0; i < 10; i++) {
177 unsigned long elapsed;
179 fio_gettime(&tv, NULL);
183 nanosleep(&ts, NULL);
184 elapsed = utime_since_now(&tv);
186 if (elapsed > ns_granularity)
187 ns_granularity = elapsed;
191 void set_genesis_time(void)
193 fio_gettime(&genesis, NULL);
196 void fill_start_time(struct timeval *t)
198 memcpy(t, &genesis, sizeof(genesis));