Skip to content

Huge CPU Load on ARM based board for While loop

An answer to this question on Stack Overflow.

Question

I have an iMX6 board and one of my application was taking much CPU without doing much work.. I wrote a sample code instead of just posting the original application

#include <stdio.h>
int main(int argc, char *argv[])
{
        printf("Hello World\r\n");
        while(1);
        return 0;
}

This is taking 25% of the CPU Load.. Can you please tell me what I can do to reduce the CPU Load

Update:

Adding a sleep of 50 microsecond reduced the CPU Load to directly 2%

#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
        printf("Hello World\r\n");
        while(1)
        {
                usleep(50);
        }
        return 0;
}

Answer

This is an example of busy looping.

The while loop is consuming all the available resources of one of your cores. Since you have four cores, you're seeing 25% CPU load.

You can cause a timed-delay that won't use any CPU resources as follows:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int main()
{
  pollingDelay = 100
  //do stuff
  //sleep:
  #ifdef _WIN32
  Sleep(pollingDelay);
  #else
  usleep(pollingDelay*1000);  /* sleep for 100 milliSeconds */
  #endif
  //do stuff again
  return 0;
}

If you want to wait for the user, the following works. Yyou may need to do something more complicated if the user defiantly presses keys before enter.

printf("Press ENTER key to Continue\n");  
getchar();