How to limit CPU usage in Python

Jerry Hill malaclypse2 at gmail.com
Thu Sep 20 13:08:57 EDT 2012


On Thu, Sep 20, 2012 at 11:12 AM, Rolando Cañer Roblejo
<rolando.caner at cnic.edu.cu> wrote:
> Hi all,
>
> Is it possible for me to put a limit in the amount of processor usage (%
> CPU) that my current python script is using? Is there any module useful for
> this task? I saw Resource module but I think it is not the module I am
> looking for. Some people recommend to use nice and cpulimit unix tools, but
> those are external to python and I prefer a python solution. I am working
> with Linux (Ubuntu 10.04).

Maximum percentage of CPU used isn't normally something you control.
The only way I know of to do it involves having another process
monitor the thing you want to control and sending signals to stop and
start it (e.g., http://cpulimit.sourceforge.net/).

Typically, you instead want to control the priority (so that higher
priority apps can easily take more CPU time).  That's what nice is for
(http://docs.python.org/library/os.html#os.nice).  If you want to
limit a process in the same way that ulimit does, then the resources
module is what you want
(http://docs.python.org/library/resource.html#resource.setrlimit).

Is there a particular reason that you'd rather have your CPU sitting
idle, rather than continuing with whatever code is waiting to be run?
I'm having a hard time understanding what problem you might be having
that some combination of setting the nice level and imposing resource
limits won't handle.

-- 
Jerry



More information about the Python-list mailing list