python - 通过Python计算进程cpu使用率

标签 python windows pywin32

我正在尝试(通过 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 程序(占用 28% 的 cpu 利用率)时,代码显示 100% 和 98%。这不好。

因此,我要求使用 Python 中的 GetSystemTimes() 函数(使用 pywin32)计算进程 cpu 使用情况的代码。

提前致谢。

最佳答案

经过更多研究,我找到了解决方案。

因此,为了获得进程 cpu 使用率的百分比,我们需要一些参数:

1。系统时间

要计算这个,我们需要用户模式时间、内核模式时间和 空闲模式时间:

    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

2。进程用户态时间和进程内核时间

首先要获取这些参数,我们需要创建一个新的进程句柄,然后我们才能获取进程用户态时间和进程内核时间:

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()

关于python - 通过Python计算进程cpu使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34614464/

相关文章:

python - 如何在 pytest -k 命令行选项中包含正斜杠 "/"

python - 如何使用pythonlogging.info模块在文件中写入 'list data'

windows - 如何使 Windows 键成为 Windows 下的 IntelliJ IDEA Command/Meta 键?

windows - 如何在 Windows 中找到哪个程序正在使用端口 80?

winapi - 非阻塞http请求循环

python - 在 Windows 中使用 python 更改目录创建时间 (ctime)

python - 在 Linux 中检测文件打开

python - 编写 django Rest 序列化器时遇到的问题

对于同一网络路径,Python os.path.exists 在 Windows 10 上返回 false,在 Windows 7 上返回 true

Python win32api 注册表项更改