开发者

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

     开发者_Python百科   unsigned long elapsedTime() {
            return ((unsigned long) clock() - begTime) / CLOCKS_PER_SEC;
        }

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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜