I made this short program in c but whenever i run it my pc's fan starts spinning really fast. Am i doing something in the wrong way or is the time library just cpu intensive somehow? Here is the code:
#include <stdio.h>
#include <time.h>
void delay(int seconds){
int clocks_to_wait = seconds * CLOCKS_PER_SEC;
clock_t time = clock();
while(clock() < time + clocks_to_wait){
}
}
int main(){
while(1){
printf("\r");
printf("-");
delay(1);
printf("\r");
printf("\\");
delay(1);
printf("\r");
printf("|");
delay(1);
printf("\r");
printf("/");
delay(1);
printf("\r");
printf("-");
delay(1);
}
return 0;
}
My guess is that the empty while loop is making the processor go hot? Am i right?
Edit: Problem solved, source: Simple <Time.h> program takes large amount CPU
Yes, an emtpy while loop like this will just use up 100% of the CPU time busy-waiting until the time catches up to however long you want to wait.
If you want to wait without burning CPU time (and wasting battery heating things up and running the fan), you need to use an OS delay that waits without using CPU. On Posix (Linux, OSX, UNIX, etc) systems, that is the sleep
, which sleeps for a specified number of seconds, or the nanosleep
call which sleeps for a timespec
which specifies the delay in nanoseconds.
In your case, just replace the delay(1);
calls with sleep(1);