简体   繁体   中英

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;
}

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM