我试图通过pid获取进程cpu的使用情况。我做了一些关于它的研究,我发现我可以使用GetSystemTimes()函数来计算它。 我在此链接中找到了计算:http://www.codeproject.com/Articles/10258/How-to-get-CPU-usage-of-processes-and-threads
我需要Python中的这段代码但是我不知道如何做到这一点。 所以我找到了这段代码:https://sites.google.com/site/cadspython/home/modules/calcprocesscpuusage-py
我试图运行它,一切都运行正常,但是当我运行一个小程序(从cpu利用率中占28%)时,代码显示我100%和98%。这不好。
所以,我要求一个代码,通过在Python中使用GetSystemTimes()函数计算进程cpu使用率(使用pywin32)。
提前致谢。
答案 0 :(得分:1)
经过一番研究后,我找到了解决方案。
因此,为了获得进程cpu使用率的百分比,我们需要一些参数:
要计算这个,我们需要用户模式时间,内核模式时间和 空闲模式时间:
from ctypes import *
import time
class FILETIME(Structure):
_fields_ = [
("dwLowDateTime", DWORD),
("dwHighDateTime", DWORD)]
def GetSystemTimes():
"""
Uses the function GetSystemTimes() (win32) in order to get the user mode time, kernel mode time and idle mode time
:return: user time, kernel time and idle time (Dictinary)
"""
__GetSystemTimes = windll.kernel32.GetSystemTimes
idleTime, kernelTime, userTime = FILETIME(), FILETIME(), FILETIME()
success = __GetSystemTimes(
byref(idleTime),
byref(kernelTime),
byref(userTime))
assert success, ctypes.WinError(ctypes.GetLastError())[1]
return {
"idleTime": idleTime.dwLowDateTime,
"kernelTime": kernelTime.dwLowDateTime,
"userTime": userTime.dwLowDateTime
}
def get_sys():
FirstSystemTimes = GetSystemTimes()
time.sleep(SLEEP_TIME_1_5)
SecSystemTimes = GetSystemTimes()
"""
The total amount of time the system has operated since the last measurement is calculated by getting
kernel + user
"""
usr = SecSystemTimes['userTime'] - FirstSystemTimes['userTime']
ker = SecSystemTimes['kernelTime'] - FirstSystemTimes['kernelTime']
idl = SecSystemTimes['idleTime'] - FirstSystemTimes['idleTime']
sys = usr + ker
return sys
要首先获取这些参数,我们需要创建一个新的流程句柄,然后我们将能够获得流程用户模式时间并处理内核时间:
def cpu_process_util(pid):
"""
Returns the process usage of CPU
Source: http://www.philosophicalgeek.com/2009/01/03/determine-cpu-usage-of-current-process-c-and-c/
:return: Process CPU usage (int)
"""
# Creates a process handle
proc = win32api.OpenProcess(ALL_PROCESS_ACCESS, False, pid)
FirstProcessTimes = win32process.GetProcessTimes(proc)
time.sleep(SLEEP_TIME_1_5)
SecProcessTimes = win32process.GetProcessTimes(proc)
"""
Process CPU usage is calculated by getting the total amount of time
the system has operated since the last measurement
made up of kernel + user) and the total
amount of time the process has run (kernel + user).
"""
proc_time_user_prev = FirstProcessTimes['UserTime']
proc_time_kernel_prev = FirstProcessTimes['KernelTime']
proc_time_user = SecProcessTimes['UserTime']
proc_time_kernel = SecProcessTimes['KernelTime']
proc_usr = proc_time_user - proc_time_user_prev
proc_ker = proc_time_kernel - proc_time_kernel_prev
proc_total_time = proc_usr + proc_ker
return (100 * proc_total_time) / get_sys()