gettimeofday is suitable for many general-purpose timing tasks. However, there are scenarios where its granularity is insufficient for precise measurement and timestamping.

The sample C program below demonstrates that the resolution of the gettimeofday function may not always be sufficient to distinguish between consecutive time measurements.

For example, If you are trying to measure the performance of a code snippet, debug a race condition, or address numerous other scenarios, you may be better off using a different method of measuring time.

  • The program initializes the random number generator with the current time.
  • It enters a loop for a specified number of iterations (10 change if needed).
  • Within each iteration, it starts by obtaining the current time using gettimeofday.
  • It then enters a nested loop where it continuously calls gettimeofday until a different time value is returned.
  • During this loop, it keeps track of how many times the same time value is returned in succession.
  • Once a different time value is detected, it exits the nested loop and prints out the number of times the same value was returned.
  • After printing, it introduces a random sleep duration between 0.1 and 0.9 milliseconds using usleep.
  • The program repeats the above steps for the specified number of iterations (10).
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/time.h>
    
    int main() {
        int repetitions = 10;
    
        for (int i = 0; i < repetitions; i++) {
            struct timeval last_time, current_time;
            gettimeofday(&last_time, NULL); // Get initial time
            int count = 0;
    
            while (1) {
                gettimeofday(&current_time, NULL); // Get current time
    
                // Check if the current time is different from the previous time
                if (current_time.tv_sec != last_time.tv_sec || current_time.tv_usec != last_time.tv_usec) {
                    // Print the number of times the same value was returned
                    printf("Run %d: Number of times the same value was returned: %d\n", i + 1, count);
                    break;
                }
    
                count++; // Increment count if the same value is returned
            }
        }
    
        return 0;
    }
    

Example output

Run 1: Number of times the same value was returned: 18
Run 2: Number of times the same value was returned: 30
Run 3: Number of times the same value was returned: 24
Run 4: Number of times the same value was returned: 45
Run 5: Number of times the same value was returned: 34
Run 6: Number of times the same value was returned: 45
Run 7: Number of times the same value was returned: 47
Run 8: Number of times the same value was returned: 46
Run 9: Number of times the same value was returned: 46
Run 10: Number of times the same value was returned: 46