CPU Usage Per Process in Python

UnkwnTech picture UnkwnTech · Nov 9, 2008 · Viewed 29k times · Source

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.

Answer

gimel picture gimel · Nov 9, 2008
>>> 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.