0

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

Gurneet singh
  • 135
  • 1
  • 6
  • 1
    `while(clock() < time + clocks_to_wait)` this is called [polling](https://en.wikipedia.org/wiki/Polling_(computer_science)) and is the worst way ever to check status. You need to use a timer (in asynchronous programs) or sleep instead – phuclv Feb 01 '21 at 00:38

1 Answers1

3

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);

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226