difftime() function in C++

In this guide, you will learn what is difftime() function is in C++ programming and how to use it with an example.

1. difftime() Function Overview

The difftime() function in C++ is used to compute the difference between two calendar times and return the difference in seconds. This function provides a safe way to perform such a subtraction, taking into account the possible peculiarities of the system's time representation. It's defined in the <ctime> header file.


double difftime(time_t time_end, time_t time_start);


- time_end: The end time.

- time_start: The start time.

2. Source Code Example

#include <iostream>
#include <ctime>

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

    // Get the current calendar time as start time

    // Simulate some processing delay using for loop
    for (int i = 0; i < 100000000; i++);

    // Get the current calendar time as end time

    // Calculate the difference
    difference = difftime(end_time, start_time);

    // Print the time difference in seconds
    std::cout << "Time taken: " << difference << " seconds." << std::endl;

    return 0;


Time taken: X seconds.

Note: The value of X will vary based on the processing time.

3. Explanation

1. Two time_t variables named start_time and end_time are declared.

2. The time() function is called with the address of start_time to store the starting time.

3. A loop is used to simulate some processing delay.

4. The time() function is then called again to get the ending time.

5. The difftime() function calculates the difference in seconds between the end time and the start time.

6. The result is printed to the console, displaying the time taken for the simulated processing.