C difftime()

The difftime() function is defined in the time.h header file. It helps to find the difference, between starting time and ending time in seconds. Here two times are in calendar time, which represents the Epoch (00:00:00 on January 1, 1970).

double difftime(time_t time1, time_t time2); #where time1,time2 are objects


difftime() Parameters: 

The difftime() function takes two parameters. This function is important because no other general arithmetic operations are defined on type time_t.

Parameter Description Required / Optional
time1  the time_t object for end time Required
time2  the time_t object for start time Required

difftime() Return Value

The function returns a double value indicating the difference between time1 and time2 in seconds.

Input Return Value
time1,time2 double value(time2-time1)

Examples of difftime() 

Example 1: Working of difftime() function in C?

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

int main()
   time_t time1, time2;
   double diff;

   printf("Program Starting...\n");

   printf("5 seconds Sleeping...\n");

   diff = difftime(time2, time1);

   printf("Execution time = %f\n", diff);
   printf("Program Exiting...\n");




Program Starting ...
5 seconds Sleeping ...
Execution time = 5.000000
Program Exiting ...

Example 2: How difftime() works in C?

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

int main (){

    int sec;
    time_t t1, t2;
    // Current time
    for (sec = 1; sec <= 6; sec++) 
    //after sleep in loop.
    printf("The difference in time is  %.2f seconds", 
                 difftime(t2, t1));
    return 0;


The difference in time is 6.00 seconds