我正在尝试为我的linux服务器编写一个小的异常警报应用程序,我发现psutil非常方便的库。
但是,我不太清楚psutil.cpu_percent(interval = 1)返回psutil.cpu_times_percent(interval = 1)
之间的区别当我第一次运行前者时,我得到以下内容: -
public class UserRolesConverter1 implements Converter<String[], List<UserRoles>> {
...
@Override
public List<UserRoles> convert(String[] roles) {
cpu_times_percent(interval = 1)给了我: -
percentage avg CPU utilization:
0.2
我第二次跑同样的,我得到: - CPU百分比=
CPU percentage time:
scputimes(user=0.0, nice=0.0, system=0.0, idle=100.0, iowait=0.0, irq=0.0,
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
但是,CPU时间百分比(cpu_times_percent())给出了以下输出: -
percentage avg CPU utilization:
0.0
此外,从cpu_times()获得的CPU IO等待时间,给我以下输出:
CPU percentage time:
scputimes(user=0.2, nice=0.0, system=0.0, idle=99.8, iowait=0.0, irq=0.0,
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
然而,从上面的观察中可以看出,%iowait为零。
基于上述观察,我有以下问题: - cpu_percent()究竟返回了什么?它是用户空间+系统+%的总百分比吗? 如上所述,它如何为零? cpu_percent()和cpu_times_percent(interval = 1)之间有什么区别?为什么他们会回归不同的价值?
IO等待时间是否来自CPU空闲时间(因为如果进程被阻塞等待IO,则CPU没有执行任何操作)。 从cpu_times中提取时如何不为零,但在cpu_times_percent中显示为零?
我试图让自己理解上述方法,并决定使用哪一种方法。 我正在寻找的是总CPU利用率百分比。 同样IOwait作为百分比。
答案 0 :(得分:0)
如果您对psutil.cpu_percent
有所帮助,它会清楚地说明您第一次跑步时可能会给出0.0。因此,请psutil.cpu_times_percent
使用interval
参数,即psutil.cpu_times_percent(interval=0.1)
>>> help(psutil.cpu_times_percent)
Help on function cpu_times_percent in module psutil:
cpu_times_percent(interval=None, percpu=False)
Same as cpu_percent() but provides utilization percentages
for each specific CPU time as is returned by cpu_times().
For instance, on Linux we'll get:
>>> cpu_times_percent()
cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
>>>
*interval* and *percpu* arguments have the same meaning as in
cpu_percent().
>>> help(psutil.cpu_percent)
Help on function cpu_percent in module psutil:
cpu_percent(interval=None, percpu=False)
Return a float representing the current system-wide CPU
utilization as a percentage.
When *interval* is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When *interval* is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately (non
blocking). That means the first time this is called it will
return a meaningless 0.0 value which you should ignore.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When *percpu* is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls.
Examples:
>>> # blocking, system-wide
>>> psutil.cpu_percent(interval=1)
2.0
>>>
>>> # blocking, per-cpu
>>> psutil.cpu_percent(interval=1, percpu=True)
[2.0, 1.0]
>>>
>>> # non-blocking (percentage since last call)
>>> psutil.cpu_percent(interval=None)
2.9
>>>