difftime() function in C++

Hello Learners, Today I’m going to show you how to implement the difftime() function in C++ language.

Our function difftime() is present in the <ctime> header. Our concern about using this function is to compare between two specific times.

Syntax of the difftime() function

Prototype:

  •  difftime(time_t ending time,time_t beginning time);
  •  It takes two time_t objects as ending time and beginning time from which it returns the difference in seconds. If the ending time is greater than the beginning then our result should be negative.

 Parameters Taken:

  • Ending time: It represents the ending time when our work has done.
  • Beginning time: It represents the beginning time when our work is starting.
  • Return value: It returns the difference of two objects beginning and ending time in seconds.

Code

Below is our program where you can see that we are using the difftime() function:

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
  time_t begin, end;
  long result;

  time(&begin);
  for(int i=0; i<10000; i++)
  {
    for(int j=0; j<100000; j++)
    {
      result = i*j;
    }
  }
  time(&end);
  cout << "Time required  to finish is = " << difftime(end, begin) << " seconds";
  return 0;
}

After we run the code, we can see the given output:

Time required to finish is = 2 seconds


This function can be applied into  the C Language, the difftime() function can be used in the following versions:

ANSI/ISO 9899-1990.

Therefore,
Other C functions that are similar to the difftime() function are :

  • asctime function <time.h>
  • ctime function <time.h>
  • gmtime function <time.h>
  • localtime function <time.h>
  • mktime function <time.h>
  • strftime function <time.h>
  • time function <time.h>

Leave a Reply

Your email address will not be published. Required fields are marked *