16

I will be having a Python run 24/7 in a while loop, here is an example of the sort of program:

while True:

    print ("me again...")

But when I run it, my CPU goes to 100%! But I don't want that since my program will run for long lengths of time, etc. and I don't want my CPU getting very hot, is there anyway I can prevent this?

user151324
  • 1,270
  • 4
  • 14
  • 17

4 Answers4

18

At the end of your loop have a

time.sleep(xx) for seconds, or time.sleep(x.x) to represent partial seconds

(Please do remember to import the library time, like so: import time )

With xx being as high as possible without adversely effecting your program. Right now your program is always doing everything as fast as it can, rather than giving some time for the Pi to rest or do something else.

Butters
  • 1,597
  • 8
  • 23
16

Preface

Be sure you really need to run your task repeatedly. This is called busy waiting and almost always suboptimal. If your task is checking for the output of a subprocess, you can just subprocess.wait() for it to finish, for example. If your task is to wait for a file or directory in the filesystem to be touched, you can use pyinotify to get your code triggered from the filesystem event handled by the kernel.

Answer

This is how you write infinite loop for busy waiting without consuming too much CPU.

Python 2:

from __future__ import print_function
from __future__ import division

import time

while True:
    range(10000)       # some payload code
    print("Me again")  # some console logging
    time.sleep(0.2)    # sane sleep time of 0.1 seconds

Python 3:

import time

while True:
    range(10000)       # some payload code
    print("Me again")  # some console logging
    time.sleep(0.2)    # sane sleep time of 0.1 seconds

Evaluation

As @gnibbler tested in another answer, the presented code should not consume more than 1 % CPU on recent machines. If it still consumes too much CPU with your payload code, consider raising the time to sleep even further. On the other hand, the payload code might need to get optimized for repeated execution. For example, Caching could speed up running on unchanged data.

Credits

This answer tries to builds upon @user2301728's answer.

Bengt
  • 2,427
  • 3
  • 22
  • 26
3

I had the same issue, see my question on Stack Exchange. The solution was a combination of time.sleep(0.01) and nice. nice lowers the CPU available to an application. This is how I start the app: nice -n 19.

dotancohen
  • 302
  • 2
  • 13
1

You could also try nice -n 19 python myscript.py.

nice is a *nix utility to set the CPU priority of a task. 19 is the largest weight and consequently the slowest setting.

CyberSkull
  • 111
  • 3