Re: elapsed time 0 with std::cin
"pekka" <pekka@nospam.invalid> wrote in message
news:pan.2007.11.23.19.46.27.572718@nospam.invalid...
I'm trying to measure user input time with my Timer class object. It isn't
as easy as I expected. When using std::cin between timer start and stop, I
get zero elapsed time. For some unknown reason, the clock seems to stop
ticking during execution of std::cin.
Here's my code:
#include <ctime>
#include <iostream>
#include <string>
class Timer
{
clock_t start_, nticks_;
public:
Timer() : nticks_(0) { start(); }
~Timer() {}
void start() { start_ = clock(); }
void stop() { nticks_ = clock() - start_; }
double elapsed() const { return double(nticks_) / CLOCKS_PER_SEC; }
};
int main()
{
std::string answer;
Timer T;
// for (int n=0; n<100000000; ++n);
std::cout << "? ";
std::cin >> answer;
T.stop();
std::cout << "time elapsed: " << T.elapsed() << "\n";
}
If I use the loop at the commented line, instead of std::cin, the timer
works as expected. I can't figure out what's wrong here.
TIA
If you are looking to do a timer, you are better off using a OS specific
timer. The ctime family is really only good for precisions of 1 second.
Things like input can happen more often than 1 second. I am fairly certain
that *nix offers some form of high precision timer and I know that MS does.
You'll have to google around a bit.