difftime() function in C++

C++Server Side ProgrammingProgramming

In this article we are going to discuss the difftime() function in C++, its syntax, working and its return values.

difftime() function is an inbuilt function in C++ which is defined in header file. The function accepts two parameters of time_t type, function calculate the difference between the two times

Syntax

double difftime(time_t end, time_t beginning);

Return value

Returns the difference of the time in seconds, stored as double data type.

Example

 Live Demo

#include <stdio.h>
#include <time.h>
int main () {
   time_t now;
   struct tm newyear;
   double seconds;
   time(&now); /* get current time; */
   newyear = *localtime(&now);
   newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;
   newyear.tm_mon = 0; newyear.tm_mday = 1;
   seconds = difftime(now,mktime(&newyear));
   printf ("%.f seconds since new year in the current timezone.\n", seconds);
   return 0;
}

Output

If we run the above code it will generate the following output −

3351041 seconds since new year in the current timezone.

Example

#include <iostream>
#include <ctime>
using namespace std;
int main() {
   time_t start, ending;
   long addition;
   time(&start);
   for (int i = 0;
   i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   }
   for (int i = 0; i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   } for (int i = 0; i < 50000; i++) {
      for (int j = 0; j < 50000; j++);
   } time(&ending);
   cout << "Total time required = " << difftime(ending, start) << " seconds " << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Total time required = 37 seconds
raja
Published on 28-Feb-2020 06:00:26
Advertisements