for i in range(10):
p = psutil.Process(3301)
print p.cpu_percent(interval=0.1)
结果:
9.9 0.0 0.0 0.0 0.0 9.9 0.0 9.9 0.0 0.0
所以如果你想得到一个进程对象的CPU百分比,你可以在一定时间内取平均值。
test_list = []
for i in range(10):
p = psutil.Process(6601)
p_cpu = p.cpu_percent(interval=0.1)
test_list.append(p_cpu)
print float(sum(test_list))/len(test_list)
When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called a second time with at least 0.1 seconds between calls.
还有一个警告,禁止对单个调用使用interval=None:
Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.
如果使用interval=None,请确保与以前的调用相比调用.cpu_percent。
p = psutil.Process(pid=pid)
p.cpu_percent(interval=None)
for i in range(100):
usage = p.cpu_percent(interval=None)
# do other things
而不是:
for i in range(100):
p = psutil.Process(pid=pid)
p.cpu_percent(interval=None)
# do other things
根据我自己的代码:
进程对象的cpu是可变的。我给你做了一些测试。
结果:
9.9 0.0 0.0 0.0 0.0 9.9 0.0 9.9 0.0 0.0
所以如果你想得到一个进程对象的CPU百分比,你可以在一定时间内取平均值。
结果:
1.98
这种行为是documented:
还有一个警告,禁止对单个调用使用
interval=None
:如果使用
interval=None
,请确保与以前的调用相比调用.cpu_percent
。而不是:
相关问题 更多 >
编程相关推荐