C Library Function - difftime()

Last Updated : 8 Aug, 2026

The difftime() function is a C standard library function used to calculate the difference between two calendar times in seconds. It takes two time_t values and returns the elapsed time between the ending and starting times.

  • Calculates the time difference as ending time - starting time in seconds.
  • It is defined in the <time.h> header file and returns a value of type double.
C
#include <stdio.h>
#include <time.h>
#include <unistd.h>

// Driver Code
int main()
{
    int sec;
    time_t time1, time2;

    // Current time
    time(&time1);
    for (sec = 1; sec <= 6; sec++)
        sleep(1);

    // time after sleep in loop.
    time(&time2);
    printf("Difference is %.2f seconds",
           difftime(time2, time1));

    return 0;
}

Output
Difference is 6.00 seconds

Syntax

The syntax of difftime() function is as follows:

double difftime(time_t time2, time_t time1);

Parameters

The difftime() function takes two parameters:

  • time1: Lower bound of the time interval whose length is calculated.
  • time2: Higher bound of the time interval whose length is calculated.

where time1 and time2 are variables of type time_t which is a predefined structure for calendar times.

Return Value

  • Returns the difference between time1 and time2 (as measured in seconds).

How difftime() Works

The difftime() function calculates the elapsed time between two time_t values. It subtracts the earlier time (time1) from the later time (time2) and returns the result in seconds.

For example, if time1 represents 10:00:00 and time2 represents 10:00:06, then difftime(time2, time1) returns 6.0.

Advantages of difftime()

The difftime() function provides a simple and portable way to calculate the difference between two calendar times.

  • Makes time difference calculations easier without directly performing arithmetic on time_t values.
  • Returns the result as a double, allowing fractional seconds when supported by the implementation.

Limitations of difftime()

Although useful for general time calculations, difftime() has some limitations when used for precise performance measurement.

  • It is not intended for high-resolution benchmarking or measuring very short execution times.
  • The result depends on the accuracy and resolution of the system clock used to obtain the time_t values.
  • It measures calendar-time differences, so it may not be the best choice for measuring CPU execution time.

Difference Between difftime() and clock()

difftime() and clock() are both related to time measurement, but they serve different purposes.

Featuredifftime()clock()
PurposeDifference between calendar timesCPU time consumed by the program
Header<time.h><time.h>
InputTwo time_t valuesNo time arguments
Return typedoubleclock_t
Best suited forElapsed calendar timeMeasuring CPU execution time
Comment