Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPU Usage Per Process in Python

Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using?

Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the app is using?

Target platform is *nix, however I would like to do it on a Win host also.

like image 668
UnkwnTech Avatar asked Nov 09 '08 18:11

UnkwnTech


People also ask

How do I get CPU utilization of a process in Python?

Get current CPU usage using psutil The function psutil. cpu_percent() provides the current system-wide CPU utilization in the form of a percentage.

What is Psutil in Python?

psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoring, profiling, limiting process resources and the management of running processes.

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.

Does Python sleep consume CPU?

Does time sleep use CPU? No, it isn't CPU intensive. The documentation says: Suspend execution for the given number of seconds. Python can't actually guarantee that in every possible implementation, this means the OS will never schedule your process during a sleep.


1 Answers

>>> import os
>>> os.times()
(1.296875, 0.765625, 0.0, 0.0, 0.0)
>>> print os.times.__doc__
times() -> (utime, stime, cutime, cstime, elapsed_time)

Return a tuple of floating point numbers indicating process times.

From the (2.5) manual:

times( )

Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows.

like image 129
gimel Avatar answered Oct 11 '22 08:10

gimel