Python 电脑性能监控器:实时监测 CPU、内存、GPU 和网络
import psutil
import GPUtil
import time
import sys
import keyboard
from termcolor import colored
def print_cpu_and_memory_usage():
cpu_percent = psutil.cpu_percent()
mem = psutil.virtual_memory()
mem_percent = mem.percent
mem_used = round(mem.used / 1024 / 1024, 2)
mem_total = round(mem.total / 1024 / 1024, 2)
print(colored(f' CPU 使用率: {cpu_percent}% ({psutil.cpu_count()} 核)', 'green'))
print(colored(f' 内存使用率: {mem_percent}% ({mem_used} / {mem_total} MB)', 'green'))
def print_gpu_usage():
gpus = GPUtil.getGPUs()
for i, gpu in enumerate(gpus):
gpu_name = gpu.name
gpu_memory_total = gpu.memoryTotal
gpu_memory_used = gpu.memoryUsed
gpu_memory_free = gpu_memory_total - gpu_memory_used
gpu_memory_percent = gpu_memory_used / gpu_memory_total * 100
print(colored(f' GPU {i + 1} 型号: {gpu_name}', 'cyan'))
print(colored(f' 显存使用率: {gpu_memory_percent:.2f}% ({gpu_memory_used} / {gpu_memory_total} MB)', 'cyan'))
print(colored(f' 显存剩余大小: {gpu_memory_free:.2f} MB', 'cyan'))
def print_network_usage():
net_io = psutil.net_io_counters()
net_speed_sent = round(net_io.bytes_sent / 1024 / 1024, 2)
net_speed_recv = round(net_io.bytes_recv / 1024 / 1024, 2)
if 'en0' in psutil.net_if_stats():
print(colored(f' 有线网卡状态: {'已连接' if psutil.net_if_stats()['en0'].isup else '未连接'}', 'yellow'))
else:
print(colored(f' 有线网卡状态: 未连接', 'yellow'))
print(colored(f' 网卡上传速度: {net_speed_sent} MB/s', 'yellow'))
print(colored(f' 网卡下载速度: {net_speed_recv} MB/s', 'yellow'))
def print_instructions():
print(colored('以下是程序操作说明:', 'magenta'))
print(' 1. 按 s 键刷新数据。')
print(' 2. 按 p 键暂停/继续程序输出。')
print(' 3. 按 c 键关闭程序。')
print(colored('--------------------------------------', 'magenta'))
def print_status(status, refresh_time):
print(colored(f'当前监测状态:{status},上次刷新时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(refresh_time))}。', 'magenta'))
def refresh_data():
refresh_time = time.time()
status = '已刷新'
print(colored('正在刷新数据,请稍候......', 'magenta'))
return status, refresh_time
def pause_resume(paused):
if paused:
paused = False
status = '继续输出'
print(colored('已取消暂停,继续输出监测结果。', 'magenta'))
else:
paused = True
status = '已暂停'
print(colored('已暂停程序,停止输出监测结果。', 'magenta'))
return paused, status
def close_program():
status = '正在关闭'
refresh_time = time.time()
print(colored('正在关闭程序,请稍候......', 'magenta'))
sys.exit(0)
def main():
print_instructions()
print(colored('开始监测,按 Ctrl+C 可以结束程序。', 'magenta'))
paused = False
status = '运行中'
refresh_time = time.time()
while True:
if not paused:
print_cpu_and_memory_usage()
print_gpu_usage()
print_network_usage()
print_status(status, refresh_time)
if keyboard.is_pressed('s'): # s键
status, refresh_time = refresh_data()
time.sleep(1)
if keyboard.is_pressed('p'): # p键
paused, status = pause_resume(paused)
time.sleep(1)
if keyboard.is_pressed('c'): # c键
close_program()
time.sleep(1)
time.sleep(0.1)
if __name__ == '__main__':
main()
优化说明:
- 将一些功能拆分成函数,使主函数更加简洁易懂。
- 将程序操作说明和开始监测提示信息整合到函数中,提高代码的可读性。
- 优化了按键操作的代码逻辑,使代码更加简洁。
- 在函数中添加了返回值,提高了函数的可重用性。
使用说明:
- 确保已经安装了
psutil,GPUtil,keyboard,termcolor库。 - 运行代码后,程序会开始监测并显示系统性能信息。
- 可以按下以下按键进行操作:
s: 刷新数据p: 暂停/继续程序输出c: 关闭程序
- 按下
Ctrl+C也可以结束程序。
注意:
GPUtil库需要安装nvidia-smi工具,才能获取 GPU 信息。- 代码中使用了
en0网卡名称,如果您的系统使用其他名称,请根据实际情况进行修改。 - 由于网络速度波动较大,显示的数值仅供参考。
希望这篇文章能帮助您了解如何使用 Python 编写一个实用的电脑性能监控器。如果您有任何问题,请随时留言。
原文地址: https://www.cveoy.top/t/topic/oxYC 著作权归作者所有。请勿转载和采集!