CPU Usage Per Process in Python

泄露秘密 提交于 2019-11-27 01:22:54

问题


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.


回答1:


>>> 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.




回答2:


By using psutil:

>>> import psutil
>>> p = psutil.Process()
>>> p.cpu_times()
cputimes(user=0.06, system=0.03)
>>> p.cpu_percent(interval=1)
0.0
>>> 



回答3:


The resource module provides getrusage which can give you the information you need, at least for Unix-like platforms.

Note that CPU usage as a percentage is always measured over a time interval. Essentially, it is the amount of time taken by your program doing something divided by the interval time.

For example, if your application takes 2 seconds of CPU time over a 5 second period, then it can be said to be using 40% of the CPU.

Note that this calculation, as simple as it seems, can get tricky when using a multiprocessor system. If your application uses 7 seconds of CPU time in 5 seconds of wall clock time on a two-processor system, do you say it is uses 140% or 70% CPU?

Update: As gimel mentions, the os.times function also provides this information in a platform-independent way. The above calculation notes still apply, of course.




回答4:


Use time.clock() to get the CPU time. To get the percentage of CPU usage do CPU time elapsed/time elapsed

For example, if CPU time elapsed is 0.2 and time elapsed is 1 then the cpu usage is 20%.

Note:You have to divide by by number of processers you have. If you have 2 i.e. a dual core:

import decimal,timeit
decimal.getcontext().prec=1000
def torture():
    decimal.Decimal(2).sqrt()
    time.sleep(0.1)
import time
clock=time.clock()
while 1:
    clock=timeit.timeit(torture,number=10)
    tclock=time.clock()
    print((tclock-clock)*p)
    clock=tclock


来源:https://stackoverflow.com/questions/276281/cpu-usage-per-process-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!