Course contentsShow
← C
Lesson 890 of 1,21912. The Standard LibraryFree lesson

Measuring intervals with `difftime`

Measuring intervals with difftime

What you'll learn: How to calculate the precise number of seconds elapsed between two specific moments in time.

In C, the time_t type acts like a snapshot of a single moment. However, these snapshots are usually stored as large integers representing seconds since a specific date in 1970. If you try to subtract one from another manually, you might run into issues depending on how a specific operating system handles time. To solve this, the <time.h> library provides a specialized tool: difftime.

The stopwatch approach

Think of difftime as a digital stopwatch. You hit "start" (save a timestamp), wait for an event to finish, hit "stop" (save a second timestamp), and then ask the computer to tell you the difference.

The function signature looks like this: double difftime(time_t end, time_t beginning);

It always returns a double, which is helpful because time calculations often require the precision of floating-point numbers, even if time_t itself is an integer.

Seeing it in action

Let's imagine we want to measure how long it takes for a user to respond to a prompt. We capture the time before the input and the time after, then let difftime do the math.

#include <stdio.h>
#include <time.h>

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

    // Capture the starting moment
    time(&start_time);

    printf("Press Enter after waiting a few seconds...");
    getchar(); // Wait for user input

    // Capture the ending moment
    time(&end_time);

    // Calculate the difference (end - start)
    seconds = difftime(end_time, start_time);

    printf("You waited %.2f seconds.\n", seconds);

    return 0;
}

Why not just subtract?

While it is tempting to use the - operator (like end - start), the C standard doesn't actually mandate that time_t must be a simple count of seconds. It could be represented differently on niche hardware. By using difftime, your code becomes "portable." This means it will work correctly whether the underlying system counts time in seconds, milliseconds, or even something more exotic. It guarantees that the result you get back is a double representing the interval in seconds, regardless of how the clock is ticking under the hood.

Key takeaway

Use difftime(end, start) to safely calculate the elapsed time in seconds between two time_t values.