共计 1004 个字符,预计需要花费 3 分钟才能阅读完成。
import psutil
import time
# 获取系统所有网络接口的输入输出统计信息
previous_time = time.perf_counter()
previous_io_counters = psutil.net_io_counters(pernic=True)
while True:
# 休眠一秒钟
time.sleep(1)
# 获取系统所有网络接口的输入输出统计信息
current_time = time.perf_counter()
current_io_counters = psutil.net_io_counters(pernic=True)
time_interval = current_time - previous_time
# 计算上传和下载的字节数之差
download_bytes = current_io_counters['eth0'].bytes_recv - previous_io_counters['eth0'].bytes_recv
upload_bytes = current_io_counters['eth0'].bytes_sent - previous_io_counters['eth0'].bytes_sent
# 计算平均每秒上传和下载的字节数
duration = 1
download_speed = download_bytes / duration / 1024 / 1024 / time_interval
upload_speed = upload_bytes / duration / 1024 / 1024 / time_interval
#获取 CPU 信息
# 获取 CPU 使用率
cpu_usage = psutil.cpu_percent(interval=1)
# 获取内存总量和可用内存
mem = psutil.virtual_memory()
# total_mem = mem.total / (1024 * 1024)
# 计算内存使用百分比
memory_percent = mem.available * 100 / mem.total
# 输出上传和下载速度
print(f"Download Speed: {download_speed:.2f} MB/s, Upload Speed: {upload_speed:.2f} MB/s")
# 保存当前的输入输出统计信息
previous_time = current_time
previous_io_counters = current_io_counters
正文完
加入官方交流QQ群:778957856