C ++ time counter

I want to program C ++ code that does the time counting at the same time, while we expect the user to enter, for example, the integer result we want to see. For example, we want the user to enter two integers and select one of four operations, then write down the result. Meanwhile, the clock or computer starts counting seconds until the user records the result. Is it possible to do this in C ++, if it is not, how can I do it? Thanks...

+4
source share
2 answers

C ++ 11/14 gives you more efficient ways than the old one #include<ctime> headers of Cfor measuring time duration, using specific classes, such as steady_clock, high_resolution_clocketc., defined in the header #include<chrono>. The following code does your work very efficiently: -

#include <iostream>
#include <chrono>

using namespace std;
int main()
{
   chrono::steady_clock sc;   // create an object of `steady_clock` class
   auto start = sc.now();     // start timer

   // do stuff....

   auto end = sc.now();       // end timer (starting & ending is done by measuring the time at the moment the process started & ended respectively)
   auto time_span = static_cast<chrono::duration<double>>(end - start);   // measure time span between start & end
   cout<<"Operation took: "<<time_span.count()<<" seconds !!!";
   return 0;
}

And you finished with your work !!!!! It may seem strange at the beginning, but it works very well without any problems. Hope your problem is resolved.

+4
source

The easiest way to use std::clock_t:

#include <iostream>
#include <cstdio>
#include <ctime>

int main()
{
    std::clock_t start;
    double duration;

    start = std::clock(); // get current time

    // Do your stuff here

    duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

    std::cout << "Operation took "<< duration << "seconds" << std::endl;

    return 0;
}

There are actually many ways to do this. This is portable and does not require an additional library. As long as you need a second precision, everything will be fine.

0
source

Source: https://habr.com/ru/post/1611173/


All Articles