Open In App

difftime() function in C++

Improve
Improve
Like Article
Like
Save
Share
Report

In C++, difftime() function is defined in ctime header file. The difftime() function is used to calculate the difference between two times in a second. The function receives two time_t type inputs and calculates the difference between them.

Syntax of difftime()

double difftime(time_t end, time_t start);

Parameters

This method accepts two parameters:

start: time_t object for start time.
end: time_t object for end time.

Returns: This function returns the difference between two times in seconds.

Example of difftime() function

Below is the C++ program to demonstrate difftime() function:

C++




// C++ program to demonstrate
// example of difftime() function.
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    time_t start, ending;
    long addition;
 
    time(&start);
   
    for (int i = 0; i < 20000; i++) {
        for (int j = 0; j < 20000; j++);
    }
   
    for (int i = 0; i < 20000; i++) {
        for (int j = 0; j < 20000; j++);
    }
   
    for (int i = 0; i < 20000; i++) {
        for (int j = 0; j < 20000; j++);
    }
    time(&ending);
   
    cout << "Total time required = "
         << difftime(ending, start) << " seconds " << endl;
   
    return 0;
}


Output:

Total time required = 2 seconds

The complexity of the above method

Time Complexity: O(n^2) where n is 20000.

Auxiliary Space: O(1)


Last Updated : 21 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads