我正在尝试(通过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
我试图运行它,并且一切正常,但是当我运行一个小Python程序(从CPU利用率中获得28%的收益)时,代码显示了100%和98%。哪个不好
因此,我要一个代码,该代码通过使用Python(带有pywin32)中的GetSystemTimes()函数来计算进程cpu的使用。
提前致谢。
经过更多研究后,我找到了解决方案。
因此,为了获得进程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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句