Can we get the time between two inputs?

I was interested to see this code:

#include<iostream>
#include<conio.h>

using namespace std;

int main(){

    int a,b;

    cout << "enter 1";
    cin  >> a;

    cout << "enter 2";
     cin >> b;

    getch();
    return 0;
}  

if we can get the time interval between the input of the variables a and b sequentially.

+3
source share
2 answers

Use time()to get the current time and difftime()to calculate the difference.

#include <iostream>
#include <ctime>
#include <conio.h>
using namespace std;
int main()
{
    int a,b;
    cout<<"enter 1";
    cin>>a;
    time_t atime = time(NULL);
    cout<<"enter 2";
    cin>>b;
    time_t btime = time(NULL);
    cout << difftime(btime, atime) << " seconds passed\n";
    getch();
    return 0;
}  
+6
source

time (), difftime () has a resolution of one second.

The recommended method would be to use chrono library (C ++ 11)

#include <chrono>

// ...

// take time 0
auto Time0= chrono::system_clock::now();

// do some work ...

// take time 1
auto Time1= chrono::system_clock::now();

// print the diff (in this example: in milliseconds)
auto Duration= chrono::duration_cast<chrono::milliseconds>(Time1 - Time0).count();
cout << Duration << endl;
+2
source

All Articles