C++ Standard Library C++ STL Library

C++ <ctime> - difftime() Function



The C++ <ctime> difftime() function compute difference between two time_t objects as (time_end - time_beg) in seconds. If time_end refers to time point before time_beg, then the function returns negative result.

Syntax

double difftime (time_t time_end, time_t time_beg);

Parameters

time_beg Specify lower bound of the time interval whose length is calculated.
time_end Specify upper bound of the time interval whose length is calculated.

Return Value

Returns (time_end - time_beg) in seconds.

Example:

The example below shows the usage of difftime() function.

#include <iostream>
#include <ctime>
using namespace std;
 
int main (){
  time_t start, finish;
  long product;

  time(&start);
  for(int i = 0; i < 100000; i++)
    for(int j = 0; j < 25000; j++) 
      product = i*j;

  time(&finish);

  //calculating the time difference
  cout<<"Time taken = "<<
        difftime(finish, start)<<" seconds";   
  return 0;
}

The possible output of the above code could be:

Time taken = 6 seconds

❮ C++ <ctime> Library