Python中每个进程的CPU使用率

2024-03-28 21:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
>>> 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.

根据(2.5)手册:

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.

通过使用psutil

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

resource模块提供^{},它可以为您提供所需的信息,至少对于类Unix平台是这样。

注意,CPU使用率总是在一个时间间隔内测量的。本质上,它是程序执行某项操作所花费的时间除以间隔时间。

例如,如果您的应用程序在5秒内占用2秒的CPU时间,那么可以说它使用了40%的CPU。

请注意,这个计算,尽管看起来很简单,但在使用多处理器系统时可能会变得很棘手。如果您的应用程序在双处理器系统上使用7秒的CPU时间,而在5秒的挂钟时间内,您认为它使用140%还是70%的CPU?

更新:正如gimel所提到的,os.times函数还以独立于平台的方式提供此信息。当然,上述计算说明仍然适用。

相关问题 更多 >