Holycrabbe Holycrabbe - 1 month ago 17
C++ Question

C++ second counter

I have created a function which counts seconds, after the choice of a user. It all works, but can it be done smarter and more efficient? Because it seems very heavy and slow. Is there a lib that solves this problem? Or how can we get around it?

Here is my code:

#include <ctime>
#include <iomanip>
#include <iostream>

using namespace std;

int main() {
double a,c, x,b;

int nutid=0;

cout<<"Please enter a number: ";
cin>>a;
x = time(0);
c = a-1;

while (true) {
if (!cin) {
cout<<"... Error";
break;
}
else {
b=time(0)-x;

if(b>nutid){
cout<<setprecision(11)<<b<<endl;
nutid = b+c;
}
}
}

return 0;
}

Answer

You can measure time using the library <chrono> (since c++11)

Example:

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;

int main() {
    auto start = high_resolution_clock::now();

    // your code here

    auto end = high_resolution_clock::now();
    // you can also use 'chrono::microseconds' etc.
    cout << duration_cast<seconds>(end - start).count() << '\n';
}