Two big reasons why that's a bad idea:
- The time spent on a given loop is very dependent on the computer running it. Ever played Quake on a modern computer? The frame rates are through the roof, and I hope that's not a surprise. More powerful computers can perform more calculations in a set time. If your computer takes 10 seconds to complete a loop, a more powerful computer might finish in 5 or less, and an older computer might take significantly longer.
So, couldn't I just do this?
#include <Mmsystem.h> //timeGetTime
void Stall(unsigned long ms)
{
unsigned long start = timeGetTime();
unsigned long passed = 0;
while (passed < ms)
passed = timeGetTime() - start;
}
#include <Mmsystem.h> //timeGetTime
void Stall(unsigned long ms)
{
unsigned long start = timeGetTime();
unsigned long passed = 0;
while (passed < ms)
passed = timeGetTime() - start;
}
Yeah, that would ensure that the same time is taken to finish the function. But don't get too excited; I said two big reasons.
- Sleep functions set your thread in a sort of "do not disturb" state, allowing your operating system to perform other tasks (handling other threads, cleaning up your thread) while your thread daydreams. While a human could look at the line and interpret it as "do nothing", your computer is wasting power blowing through that empty loop as fast as it can.
So, I can do this?
#include <Mmsystem.h> //timeGetTime
#include <WinBase.h> //Sleep
void Stall(unsigned long ms)
{
unsigned long start = timeGetTime();
unsigned long passed = 0;
while (passed < ms)
{
passed = timeGetTime() - start;
Sleep(0);
}
}
#include <Mmsystem.h> //timeGetTime
#include <WinBase.h> //Sleep
void Stall(unsigned long ms)
{
unsigned long start = timeGetTime();
unsigned long passed = 0;
while (passed < ms)
{
passed = timeGetTime() - start;
Sleep(0);
}
}
Better, but it still wastes CPU resources when it doesn't have to. And if there are no other threads running, Sleep(0) immediately returns to your thread, meaning your CPU is still running at maximum speed.
Conclusion: for most applications, stick with sleep functions.