Sleep() function into a for loop

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.
Last edited on
We don't believe it unless you have proof.
Either measure the duration using clock() or using the header #include <chrono>
Well your partly right

The first program actually takes about 3300ms.
The second program takes around 4700ms.

If you remove the loop and change the delay to from anywhere from 1ms to 3000ms, it takes 15ms to run.

So what I can conclude is the sleep function is taking time start and stop. So the more times you loop, the longer the run time will be.
So, what function can i use to avoid the problem that Sleep() function is making? Thanks.
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.
Topic archived. No new replies allowed.