Timer

I need working timer that don't interrupt anything else (so no sleep();)
I found few in google, even few here, on forums, but well, some doesn't work at all and this one, the easiest one imo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
		}
};

counts seconds too slowly, 1 for about 1.5 sec.
When you say "doesn't interrupt", do you mean "won't pause other processing"?

Boost.Asio has an asynchronous timer and includes code on how to use it in their examples.

alarm(2) is another asynchronous method, but it's use is rather limited.

The simplest is to create a thread that sleeps and sets a flag that can be queried when it wakes up. Boost.Thread makes that a rather trivial exercise.

If you really need polling, then you've got the simplest implementation.

Topic archived. No new replies allowed.