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);
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).
The difftime
function returns a double
object that represents the difference in seconds between the ending and beginning times, i.e., .
If the argument for end
refers to a time before begin
, then the return value is negative.
The code below shows how the difftime
function works in C:
#include <stdio.h>#include <time.h>#include <unistd.h>int main() {// initialize variablestime_t end, begin;double difference;//store start timeprintf("Starting program execution...\n");time(&begin);//Pause programprintf("Pausing execution for 3 seconds...\n");sleep(3);//store end timetime(&end);//Compute the difference in timesdifference = difftime(end, begin);printf("The program executed in %f seconds.\n", difference);return 0;}
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