Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Limit cpu usage for a script

Is it possible for a Python script to limit the CPU power allocated to it?

Right now, I have a script (using only one core) that is using 100% of one CPU's core. I need it to use less than that amount.

Is there an equivalent to PHP's memory_limit in Python? or is there a library to manage memory allocation? (using sleep isn't a very elegant solution)

like image 507
Hakim Avatar asked Jan 13 '15 10:01

Hakim


People also ask

How do I limit CPU usage in Python?

Limiting CPU and Memory Usage Resources like CPU, memory utilised by our Python program can be controlled using the resource library. To get the processor time (in seconds) that a process can use, we can use the resource. getrlimit() method. It returns the current soft and hard limit of the resource.

How do I use CPU utilization in Python?

Get current CPU usage using psutilThe function psutil. cpu_percent() provides the current system-wide CPU utilization in the form of a percentage. It takes a parameter which is the time interval (seconds). Since CPU utilization is calculated over a period of time it is recommended to provide a time interval.


1 Answers

Maybe try Python's resource package?

The resource package is basically a wraparound of setrlimit in UNIX. So you can set constrains for CPU/Memory usage, etc.

More about setrlimit in Linux

like image 127
gameboy1024 Avatar answered Oct 06 '22 01:10

gameboy1024