Reputation: 1
I have an application with a fairly strict time limit. Occasionally we get pathological input that I need to discard. There's one loop that bottlenecks, and it has a lot of iterations. Around Xe6 or so. Anything that takes more than about 30ms is bad input and I know then I can drop it.
What is the least performance intensive way to check the time and end the loop?
I looked at QueryHighPerformanceCounter(), but that adds a pretty high overhead, more than 1ms. Besides, that's more precision than I really need. I really have no idea of the performance impact of the various timing stuff.
Any advice?
Upvotes: 0
Views: 40
Reputation: 490148
I would probably run the loop in a thread. I'd set up two Event objects: one to signal that the processing is finished, the other to signal that the thread should exit. This thread sets the first when it exits the loop. It checks the second periodically by calling (for example) WaitForSingleObject with a timeout of 0 often enough that you can expect it to do that once every few milliseconds or so. Given 1e6 iterations and 30 ms, let's say once very 30.000 iterations. If that Event is set, it exits the loop.
I'd have another thread that does a WaitForSingleObject on the first Event. When it calls WaitForSingleObject, it specifies a timeout of 30 ms. When WaitForSingleObject returns, it checks the return value. If it returned because the Event was set, the processing is done, and you can proceed. If it timed out, you set the second Event, and the next time the thread checks the Event, it sees that it's been signaled to stop processing, so it exits the loop.
That's obviously not the only possible way to do the job, but it's a pretty simple one that should have pretty minimal overhead. The only part that would happen in the loop would be the zero-timeout call to WaitForSingleObject.
At least in my testing on reasonably recent CPUs, you can expect each of those calls to take around 0.2 microseconds, so you're adding a total of around 6 microseconds to your 30 ms of processing. IOW, you're slowing the processing by considerably less than 1%. I doubt the difference in processing speed can be measured dependably, not to mention it making any significant difference.
Upvotes: 1