Unk*_*ech 14 python monitoring cpu-usage
我是否可以看到当前python应用程序使用的处理器使用量(最大值的百分比)?
场景:我的主机允许我运行我的应用程序,只要它不消耗超过X%的CPU功率,所以我希望它"关注自己"并放慢速度.那么我怎么知道应用程序使用了多少CPU?
目标平台是*nix,但是我想在Win主机上也这样做.
gim*_*mel 26
>>> 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.
Run Code Online (Sandbox Code Playgroud)
从(2.5)手册:
次()
返回一个5元组的浮点数,表示累计(处理器或其他)时间,以秒为单位.这些项目包括:用户时间,系统时间,孩子的用户时间,孩子的系统时间,以及自上一个固定点以来经过的实际时间.请参阅Unix手册页时间(2)或相应的Windows Platform API文档.可用性:Macintosh,Unix,Windows.
Gia*_*olà 12
通过使用psutil:
>>> import psutil
>>> p = psutil.Process()
>>> p.cpu_times()
cputimes(user=0.06, system=0.03)
>>> p.cpu_percent(interval=1)
0.0
>>>
Run Code Online (Sandbox Code Playgroud)