简体   繁体   中英

How to reduce CPU usage from own C programms

User C programm do cpu usage of 200% on my RPi3+. I noticed it because I wondered about the hight temperature.

I checked my other Pis with other own written C programms. Nearly the same: CPU usage 100% (Pi3 but no plus). When I kill/stop just this programm, the CPU usage and temperature drop down.

In the while(1) loop i check the gpio state (connected to a button) . If it pressed i do things depending on duration that the button is pressed. For expample print over cups or delete/change mysql data.

I read something about select() but i didnt understood the context or usage. But I understood that slowering the loop with sleeps ist not the way of art.

...
while(1)
{
   if (digitalRead(butPin)) // Button is released if this returns 1
   {
       digitalWrite(ledPin, LOW);     // Regular LED off
   }
   else 
   {
      //evalute button press
      ......
   }
...

All works fine and the pi response fast usally. But for this easy work the pi is too hot. So it also needs too much power.

EDIT:

First try: add usleep() to the end of while(1)

this reduce the CPU usage but not to low level.

usleep(0) => 200%

usleep(5) => 111%

usleep(100) => 105%

usleep(5000) => 100%

(on Raspberry 3+)

Top RPI3+ CPU 200%

You may let the OS spare resources (compute other things) by telling your program to sleep.

usleep(int timeInMicroseconds);

this will make the program sleep for timeInMicroseconds.

As your program take in account Button pushes sleeping for a even a few milliseconds shouldn't make your program less efficient in detecting pushes.

The more your program will sleep the more it will release the CPU, but also be less reactive to detect your pushes (and even doesn't detect them if the sleep period is too long). It's a balance; some trial and error should give you a good value.

#include <unistd.h>

while(1)
{
   if (digitalRead(butPin)) // Button is released if this returns 1
   {
       digitalWrite(ledPin, LOW);     // Regular LED off
   }
   else 
   {

   }
   usleep(5000); //Sleep for 5ms
}

Another option would be to use interruption: Interruption with wiringPi .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM