Difftime() C library function


Here we will see what is the difftime() function in C. The difftime() is used to get the differences between two time values.

difftime() takes two time argument, the first one is the lower bound, and the second one is the upper bound. And it returns the differences between these two arguments.

Example

#include <time.h>
#include <stdio.h>
#include <unistd.h>
main() {
   int sec;
   time_t time1, time2;
   time(&time1);
   printf("Current Time: %ld\n",time1);
   for (sec = 1; sec <= 5; sec++){
      sleep(1);
      printf("Count: %d\n",sec);
   }
   time(&time2);
   printf("Ending Time: %ld\n",time2);
   printf("Difference is %.2f seconds", difftime(time2, time1));
}

Output

Current Time: 1554918635
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Ending Time: 1554918640
Difference is 5.00 seconds

Updated on: 30-Jul-2019

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements