difftime Function in C

The difftime() is a C Library function. It computes the difference between two calendar times (time1 – time0 ) in seconds. The difftime function is present in the <time.h> header file.

 

Syntax of difftime:

The prototype of the difftime function is below:

double difftime(time_t time1, time_t time0);

 

Parameters:

The difftime function takes two time_t objects as parameters. They are the following:

time1 − This is the end time.

time0 − This is the start time.

 

Returns:

The difftime function returns the difference expressed in seconds as a double.

 

Example Program:

The below code explains how to use the difftime function in C.

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

int main()
{
    //variables
    time_t endTime, startTime;
    double timeDifference;

    //get the Current time
    printf("Starting program execution...\n\n");
    time(&startTime);

    //Pause program
    printf("Pausing execution for 6 seconds...\n\n");
    sleep(6);

    //get the Current time after sleep
    time(&endTime);

    //Compute the timeDifference in times
    timeDifference = difftime(endTime, startTime);

    printf("Time difference is %.2f seconds\n", timeDifference);
    
    return 0;
}

Output:

Starting program execution...

Pausing execution for 6 seconds...

Time difference is 6.00 seconds

 

How does the above code work?

In the above code, created two time_t objects to store the times. When the program starts execution, the time() function stores the current time in the startTime variable.

time_t endTime, startTime;
double timeDifference;

//get the Current time
printf("Starting program execution...\n\n");
time(&startTime);

 

After the execution of the code, I am calling the sleep() function to pause the code for 6 seconds. And once the program resumes, again call the time() function to store the current time in the variable endTime.

//Pause program
printf("Pausing execution for 6 seconds...\n\n");
sleep(6);

//get the Current time after sleep
time(&endTime);

 

Now in the last calling the difftime function computes the difference between the times stored in startTime and endTime in seconds.

//Compute the timeDifference in times
timeDifference = difftime(endTime, startTime);

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *