#include #include #include #include #include #include /* timeval_subtract() code taken from the GLIBC docs at gnu.org http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html */ int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) { int nsec; /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main() { struct timeval tv1, tv2, result; int x; /* let's put our calibration parameters here */ /* Let's cache usleep (if there is such a thing). It seems the first call to usleep takes longer than the rest. */ usleep(0); printf("Print elapsed time at every call to usleep()\n"); for (x = 0; x < 10; x++) { gettimeofday(&tv1, NULL); usleep(100000); gettimeofday(&tv2, NULL); timeval_subtract(&result, &tv2, &tv1); printf("Elapsed time (sec:microsec) %d:%d\n", result.tv_sec, result.tv_usec); } printf("\n"); printf("Print elapsed after the loop()\n"); gettimeofday(&tv1, NULL); for (x = 0; x < 10; x++) { usleep(100000); } gettimeofday(&tv2, NULL); printf("Elapsed time (sec:microsec) %d:%d\n", result.tv_sec, result.tv_usec); timeval_subtract(&result, &tv2, &tv1); return 0; }