gettimeofday
gettimeofday() returns the current system clock time. The return value is a list of two integers indicating the number of seconds since January 1, 1970 and the number of microseconds since the most recent second boundary.
The sampletime code shown in Listing 1.3 uses gettimeofday to measure the time it takes to sleep for 200 seconds. The gettimeofday routine could be used to measure how long it takes to write or read a file. Listing 1.4 is the pseudocode that could be used to time a write call.
Listing 1.3 sampletime.c
1 #include <stdio.h> 2 #include <sys/time.h> 3 4 struct timeval start, finish ; 5 int msec; 6 7 int main () 8 { 9 gettimeofday (&start, NULL); 10 11 sleep (200); /* wait ~ 200 seconds */ 12 13 gettimeofday (&finish, NULL); 14 15 msec = finish.tv_sec * 1000 + finish.tv_usec / 1000; 16 msec -= start.tv_sec * 1000 + start.tv_usec / 1000; 17 18 printf("Time: %d milliseconds\n", msec); 19 }
Figure 1.9 shows the building of sampletime.c and the program’s output. Using gettimeofday, the time for the sleep call on line 11 is 200009 milliseconds.
Figure 1.9 Timing using gettimeofday.
Listing 1.4 shows pseudocode for measuring the write call with the gettimeofday API. The gettimeofday routine is called before the write routine is called to get the start time. After the write call is made, gettimeofday is called again to get the end time. Then the elapse_time for the write can be calculated.
Listing 1.4 Pseudocode for Timing Write Code
1 /* get time of day before writing */ 2 if ( gettimeofday( &tp_start, NULL ) == -1 ) 3 { 4 /* error message gettimeofday failed */ 5 } 6 /* calculate elapse_time_start */ 7 /* write to disk */ 8 for ( i = 0; i < count; i++ ) 9 { 10 if ( write( fd, buf, buf_size ) == 0 ) 11 { 12 /* error message write failed */ 13 } 14 } 15 /* get time of day after write */ 16 if ( gettimeofday( &tp_end, NULL ) == -1 ) 17 { 18 /* error message gettimeofday failed */ 19 } 20 /* calculate elapse_time_new */ 21 elapse_time = elapse_time_new - elapse_time_start; 22 /* compute throughput */ 23 printf( "elapse time for write: %d \n", elapse_time );
Raw timings have limited usage when looking for performance issues. Profilers can help pinpoint the parts of your program that are using the most time.