【python获取浏览器内存和cpu占用】

from datetime import datetime

import psutil
import time


def get_process_list(process_name):
    # 获取所有正在运行的进程PID
    pid_list = psutil.pids()
    process_list = []
    for pid in pid_list:
        try:
            pid_process = psutil.Process(pid)
        except Exception as e:
            continue
        pid_name = pid_process.name()
        if process_name == pid_name:
            process_list.append(pid_process)
    return process_list


if __name__ == "__main__":
    while True:
        process_list = get_process_list("chrome.exe")
        print(len(process_list))
        chrome_cpu_percnet = 0
        chrome_mem_uss = 0
        for pid_process in process_list:
            try:
                psutil.Process(pid_process.pid)
            except Exception as e:
                continue
            chrome_mem_uss = chrome_mem_uss + pid_process.memory_full_info().uss  # USS(唯一集大小)是进程专有的内存
            pid_process.cpu_percent(None)
        time.sleep(1)
        # 第一次调用pid_process.cpu_percent(None)得到的是0
        # 第二次调用pid_process.cpu_percent(None)得到的是从上一次调用同一个进程对象的cpu_percent(None)方法到第二次调用之间的cpu利用率(cpu利用率是计算一段时间内cpu计算时间/总时间)
        for pid_process in process_list:
            try:
                psutil.Process(pid_process.pid)
            except Exception as e:
                continue
            chrome_cpu_percnet = chrome_cpu_percnet + pid_process.cpu_percent(None)
        chrome_mem_uss_str = str(round(chrome_mem_uss / 1024 / 1024, 2))
        chrome_cpu_percnet_str = str(round(chrome_cpu_percnet, 2))
        print("浏览器内存占用:",chrome_mem_uss_str,"cpu使用率:",chrome_cpu_percnet_str)
        with open("mem_and_cpu", 'a') as mem_file:
            now_time = datetime.fromtimestamp(round(time.time(), 0))
            mem_file.write(str(now_time) + "," + chrome_mem_uss_str + "," + chrome_cpu_percnet_str +"\n")




你可能感兴趣的:(python,python,测试工具)