What is difftime in C?

The difftime function in C returns the difference in seconds between two time objects.

To use the difftime function, you will need to include the <time.h> library in the program, as shown below:

#include <time.h>

The prototype of the difftime function is below:

double difftime(time_t end, time_t begin);

Parameters

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

  • end : end time.
  • begin : start time.

Note: The two objects are specified in calendar time, which represents the time elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC).

Return Value

The difftime function returns a double object that represents the difference in seconds between the ending and beginning times, i.e., endbeginend - begin.

If the argument for end refers to a time before begin, then the return value is negative.

Example

The code below shows how the difftime function works in C:

#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main() {
// initialize variables
time_t end, begin;
double difference;
//store start time
printf("Starting program execution...\n");
time(&begin);
//Pause program
printf("Pausing execution for 3 seconds...\n");
sleep(3);
//store end time
time(&end);
//Compute the difference in times
difference = difftime(end, begin);
printf("The program executed in %f seconds.\n", difference);
return 0;
}

Explanation

Firstly, two time_t variables are initialized to store the start and end times of the program.

When the program begins execution, the time() function stores the current time in the begin variable.

The program is then paused, using the sleep() function, to allow for time to elapse. Once the program resumes, the time() function stores the current time in the variable end.

Finally, the difftime function computes the difference in seconds between the times stored in end and begin. This difference is then written to stdout.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved