Is there a multi-platform sleep/pause function?

Is there a multi-platform version of sleep(time)?

I was using while (true) to control some code that was supposed to run for a designated amount of time. I noticed the processor load spike by 40-60%. As there was no input to slow down execution, it was tearing through the code in the while loop and repeating as quickly as possible. Looked up a way to slow it down and discovered sleep(# of milliseconds in Windows.h. Is there either: a) a better way to go about controlling the rate of execution; or b) a cross-platform variant of sleep(time)?
Generally sleep() is not recommended. The alternative is to use events and signals to control the flow of a program. The reason for this is that programs should not be 'hanging' themselves but instead allow the user to do other tasks while the program is waiting for some new event to process.

while(true) is a brutal way to pause a program as you've seen. Depending on how you've implemented your 'timer' the actual sleep time could have been dependent on processor speed and the actual hardware you use instead of the equivalent seconds you programed it for.

All this said, there are still applications for a sleep() function and it is much better than most while variants. Since sleep functions make use of the system time they are OS specific but most OS do have some sort of sleep() function. It's just a matter of finding the right header.
Yes, it's called std::this_thread::sleep_for()

It's also available in boost, if your compiler doesn't support it directly:
Last edited on
Topic archived. No new replies allowed.