Andre Ahmed
Andre Ahmed

Reputation: 1889

C++ Timer Problem

I've written a timer class. After starting the timer, I would like to know if 20 seconds has been passed or not, if it is, I would like to call a function or perform a block of code. That class doesn't work but I Don't know why .

EDIT: By it doesn't work I mean that isTimeTout(seconds) always return true; I would like just to see if few seconds has been passed, and based on that do an action. class timer { private: unsigned long begTime; public: void start() { begTime = clock(); }

        unsigned long elapsedTime() {
            return ((unsigned long) clock() - begTime) / CLOCKS_PER_SEC;
        }

        bool isTimeout(unsigned long seconds) {
            return seconds >= elapsedTime();
        }
};

Upvotes: 0

Views: 396

Answers (3)

Mysticial
Mysticial

Reputation: 471529

Since you're on Windows, you can stick with using clock().

The error is here:

return seconds >= elapsedTime();

it should be:

return seconds <= elapsedTime();

What you have right now will return true when less than 20 seconds has elapsed. Flipping the comparison should fix it.

Upvotes: 1

Josh Polk
Josh Polk

Reputation: 265

Try using time() and difftime() like stated above. I've had this problem before too :)

Upvotes: 0

Michael Burr
Michael Burr

Reputation: 340436

clock() measures CPU time not wall time. Try using time() along with difftime() instead.

Upvotes: 3

Related Questions