Hi everyone, i'm learning to program in C++ and i'm making a program right now, but i found a problem with the Sleep() function using the <windows.h> library.
Here's the deal:
This code waits 3 seconds in total:
1 2 3
for(int i = 0; i < 30; i++){
Sleep(100);
}
But, if i write the same code like this:
1 2 3 4 5
for(int i = 0; i < 30; i++){
for(int h = 0; h < 10; h++){
Sleep(10);
}
}
It takes like 4 seconds! And i don't know why. If someone could tell me what am i missing i would be very appreciated.
Well since your for loop doesn't actually do anything but pause for a number of ms, you could change the number of each sleep(number) so that depending on the number of loops it will account for the lag time it takes to start and stop.
or simply take out the for loop as in this example, it doesn't serve a purpose.
I can' t test it right now but something like this could be more accurate.
int numberms=100;
int timestoloop=30;
for(int i = 0; i < timestoloop; i++){
Sleep(numberms-timestoloop);
}
The way I understand it is, Sleep() guarantees a minimum amount of time to sleep. When it expires, the thread that called it is placed in a queue to execute again, and when other threads that are currently running or queued (or with higher priority) complete, the calling task gets control of the CPU and is able to run. Frequently this is a short, or even unnoticeable, delay, but when you nest a bunch of loops around your Sleep() call, the delays will add up.