Here's what I do. Watch your calcs at the end.
Code:
int rc ;
struct timeval tv_start, tv_end ;
struct timezone tz ;
rc = gettimeofday(&tv_start, &tz) ;
if (rc) {
printf("gettimeofday() failed, rc = %d\n", rc) ;
return rc ;
}
// do something...
rc = gettimeofday(&tv_end, &tz) ;
if (rc) {
printf("gettimeofday() failed, rc = %d\n", rc) ;
return rc ;
}
printf("tv_start = %ld.%ld, tv_end = %ld.%ld\n", tv_start.tv_sec, tv_start.tv_usec, tv_end.tv_sec, tv_end.tv_usec) ;
if ( tv_end.tv_usec < tv_start.tv_usec) {
// printf("tv_start_usec - tv_end_usec = %d\n", tv_start.tv_usec - tv_end.tv_usec) ;
tv_end.tv_sec-- ; // borrow from seconds
tv_end.tv_usec += 1000000 ; // a usec is 1 milllionth of a second.
}
printf("Elapsed Time (seconds) was %ld.%06ld\n", (tv_end.tv_sec- tv_start.tv_sec), (tv_end.tv_usec - tv_start.tv_usec)) ;