【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")




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值