How does the Sleep delay function avoid CPU usage while waiting?

Apr 3, 2012 at 9:43pm
Hello! I notice that when I use Sleep(ms) from the <windows> library to delay a program, the fan does not start up on my computer, indicating that the cpu is working hard.

The loop below will execute once per second.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <time.h>
#include <windows.h>

clock_t loop_start_tick;
bool quit = false;

while(!quit)
{
    loop_start_tick = clock();//get the start time of the loop

   //main code goes here


    if( (clock() - loop_start_tick) < CLOCKS_PER_SECOND ) //if loop was < 1 sec
    {
        Sleep(CLOCKS_PER_SEC - (clock()-loop_start_tick)); //then delay
    }

}


However, with a function created using Just the time library, delaying by using an empty while loop:
1
2
3
4
5
6
7
clock_t endwait; //will store a future value of ticks to end the while loop

    if( (clock() - loop_start_tick) < CLOCKS_PER_SECOND ) //if loop was < 1 sec
    {
        endwait = clock() + (CLOCKS_PER_SEC - (clock()-loop_start_tick) );
        while (clock() < endwait){}  //wait 
    }


the CPU fan starts up when the program is run, indicating that an empty while loop is still using CPU resources.

Here are some questions, I would be delighted if you could answer.

#1-Is there a way to write a delay function which does not use the CPU while waiting?
#2-is there already such a function as part of the C language other than Sleep() in the windows library?

#3-How does the Sleep function avoid using CPU power?

Thank you for your time and efforts!
Apr 3, 2012 at 9:55pm
The Sleep function will be handled by the operating system that has better control over the hardware. I don't know the details how this works, but I don't think it's possible to write such a function yourself. C has no standard sleep function, but I think C++11 has.
Apr 3, 2012 at 9:57pm
closed account (S6k9GNh0)
iirc, to "sleep" is actually an OS-specific mechanism which uses the CPU scheduler. However, that's as far as I can go and I'm not entirely certain of that even. I'm curious myself.

A lot of threading API's provide a wrapped version of the given OS's sleep. For instance, Boost.Thread (and std::thread is probably the same exact way) has this: http://www.boost.org/doc/libs/1_49_0/doc/html/thread/thread_management.html#thread.thread_management.thread.sleep
Last edited on Apr 3, 2012 at 10:01pm
Topic archived. No new replies allowed.