difftime() Function Example in C Programming

In this source code example, we will see how to use the difftime() function in C programming with an example.

difftime() Function Overview

The difftime() function in C computes the difference between two time_t values, returning the number of elapsed seconds between the two points. It's useful when you want to determine the time interval between two moments. The function resides within the time.h library. 

Key Points:

- You'll need the time.h header to use difftime()

- The function returns the difference in seconds as a double type. 

- The first argument to difftime() is the end time, and the second is the start time. 

- Useful in scenarios such as calculating the duration of an operation or the age of a file.

Source Code Example

#include <stdio.h>
#include <time.h>  // Required for difftime(), time(), and other time functions

int main() {
    time_t start_time, end_time;
    double elapsed_seconds;

    // Get the current calendar time as the start time
    start_time = time(NULL);

    // Simulating a delay or an operation for the sake of this example
    for (long int i = 0; i < 10000000; i++);

    // Get the current calendar time again as the end time
    end_time = time(NULL);

    // Compute the difference between the two times
    elapsed_seconds = difftime(end_time, start_time);

    printf("The operation took %f seconds.\n", elapsed_seconds);

    return 0;
}

Output

The operation took 0.000000 seconds.
(Note: The output duration might vary based on the system's speed and the simulated delay.)

Explanation

1. Necessary header files are incorporated: stdio.h for input/output functions and time.h for difftime(), time(), and other time-related functions.

2. Within the main() function, we first capture the current calendar time as the start_time using time(NULL).

3. A loop is then used to simulate a delay or an operation. The actual duration of this loop can differ based on system speed and compiler optimizations.

4. The current calendar time is again captured, now as the end_time.

5. difftime() is utilized to calculate the time difference between end_time and start_time.

6. The elapsed time in seconds is printed to the console.

In real-world applications, difftime() can be extremely handy. For instance, when determining how long it takes for a piece of code to run or when checking the age difference between two files.


Comments