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!