Overview #
The difftime() function calculates the difference between two calendar times.
The result is returned as a value of type double representing the elapsed time in seconds.
difftime() is commonly used to determine the duration between two events.
Header File #
#include <time.h>
Man Pages #
man 3 difftime
Function Prototype #
double difftime(time_t end, time_t beginning);
Parameters #
| Parameter | Description |
|---|---|
end |
Ending calendar time. |
beginning |
Starting calendar time. |
Return Value #
Returns the difference between end and beginning in seconds as a value of type double.
The returned value can be:
- Positive if
endis later thanbeginning. - Zero if both times are equal.
- Negative if
endis earlier thanbeginning.
Examples #
Example 1 โ Calculate Elapsed Time #
main.c #
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
time_t start, end;
double elapsed_time;
start = time(NULL);
sleep(5);
end = time(NULL);
elapsed_time = difftime(end, start);
printf("Elapsed Time = %.0f seconds\n", elapsed_time);
return 0;
}
Output #
Elapsed Time = 5 seconds
The output may vary slightly depending on your system.
Explanation #
start = time(NULL);
Stores the starting calendar time.
sleep(5);
Pauses the program for five seconds.
end = time(NULL);
Stores the ending calendar time.
elapsed_time = difftime(end, start);
Calculates the difference between the two calendar times.
The returned value is expressed in seconds.
Example 2 โ Calculate the Difference Between Two Time Values #
main.c #
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t start = 100;
time_t end = 250;
printf("Difference = %.0f seconds\n",
difftime(end, start));
return 0;
}
Output #
Difference = 150 seconds
Explanation #
time_t start = 100;
time_t end = 250;
Creates two calendar time values.
difftime(end, start);
Returns the difference between the two values.
Since 250 - 100 = 150, the function returns 150.
Notes #
difftime()returns the difference between two calendar times.- The returned value is expressed in seconds.
- The return type is
double. endshould normally represent a later time thanbeginning.difftime()should be preferred over manually subtracting twotime_tvalues because it provides a portable implementation regardless of howtime_tis represented.
Related Functions #
time()clock()clock_gettime()ctime()localtime()gmtime()