#include #include #include #include /* calculate the time-difference between t1 and t2, assuming t2 comes no earlier * then t1. * stores the time difference in 'diff'. * returns 0 on success, -1 if t1 comes after t2. */ int time_diff(struct timeval *t1, struct timeval *t2, struct timeval *diff) { /* sanity check. */ if (t1->tv_sec > t2->tv_sec || (t1->tv_sec == t2->tv_sec && t1->tv_usec > t2->tv_usec)) return -1; if (t2->tv_sec == t1->tv_sec) { diff->tv_sec = 0; diff->tv_usec = t2->tv_usec - t2->tv_usec; } else { diff->tv_sec = t2->tv_sec - t1->tv_sec; if (t2->tv_usec >= t1->tv_usec) diff->tv_usec = t2->tv_usec - t1->tv_usec; else { diff->tv_usec = 1000000 + t2->tv_usec - t1->tv_usec; diff->tv_sec -= 1; } } return 0; } /* perform a busy-wait for a given number of seconds (3 in our example). * if there's an error (e.g. time went backwards), terminate immediately. */ int main() { struct timeval start; struct timeval now; struct timeval diff; int delay = 3; if (gettimeofday(&start, NULL)) { fprintf(stderr, "Error getting start time - %s\n", strerror(errno)); return 1; } printf("Busy-waiting %d seconds. time before: %lu:%lu\n", delay, start.tv_sec, start.tv_usec); /* perform the delay. */ while (1) { /* get the time, calculate diff from start, terminate if it is time. */ if (gettimeofday(&now, NULL)) { fprintf(stderr, "Error getting 'now' time - %s\n", strerror(errno)); return 1; } if (time_diff(&start, &now, &diff)) { fprintf(stderr, "Error - time just sliped backwards, now - %lu:%lu\n", now.tv_sec, now.tv_usec); return 1; } if (diff.tv_sec >= delay) break; } printf("time after: %lu:%lu\n", now.tv_sec, now.tv_usec); printf("diff: %lu:%lu\n", diff.tv_sec, diff.tv_usec); return 0; }