【Python用psutil获取CPU、内存等硬件信息】


psutil是Python的一个第三方库,提供了各种强大的硬件信息查阅功能,是标准库推荐的第三方库。一般conda会自行携带这个模块,如果未安装,可直接pip

pip install psutil

CPU 相关

  • 函数 功能
  • cpu_count() CPU核心数/线程数
  • cpu_freq() CPU频率
  • cpu_times() CPU时间
  • cpu_stats() CPU统计信息
  • cpu_percent() CPU使用率

以i9-13900H为例,是一个6大核8小核总计20线程的CPU,则其核心数和线程数为

import psutil
print(psutil.cpu_count(logical=False))  # 返回核心数14    
print(psutil.cpu_count())               # 进程数20
print(psutil.cpu_freq())                # CPU频率
# scpufreq(current=2600.0, min=0.0, max=2600.0)

cpu_timescpu_percent功能类似,都是统计CPU的时间占用,前者主要统计CPU 的用户/系统/空闲时间;后者则返回某个时间段内CPU的占用比例,可通过interval来调节统计的延时。二者均提供percpu参数,为True时,将返回每个线程的占用情况。

print(psutil.cpu_times())
# scputimes(user=217520.578125, system=74740.26562500186, idle=8452631.640624998, interrupt=3238.703125, dpc=2513.390625)

# 0.5秒内每个现成的资源利用占比
print(psutil.cpu_percent(interval=0.5, percpu=True))  

# [0.0, 0.0, 0.0, 0.0, 0.0, 2.9, 11.8, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 24.2, 0.0, 0.0, 0.0, 32.3, 0.0, 0.0]

通过cpu_stats函数可查看CPU 的统计信息,包括上下文切换、中断、软中断,以及系统调用次数等等

print(psutil.cpu_stats())
# scpustats(ctx_switches=3751269358, interrupts=3638215162, soft_interrupts=0, syscalls=443301569) 

内存相关

  • virtual_memory() 内存利用情况
  • swap_memory() 交换内存

这两个函数的返回值均有下面几个属性

total 总内存
used 已使用的内存
percent 内存使用率

此外,virtual_memory返回值中有available属性,表示可用内存,示例如下

vm = psutil.virtual_memory()
GB = 1024*1024*1024
print(vm.total/GB, "GB")
# 31.741661071777344 GB
print(vm.available/GB, "GB")
# 15.915771484375 GB
print(vm.percent, "%")
# 49.9 %
print(vm.used/GB, "GB")
# 15.825889587402344 GB
print(psutil.swap_memory()) # 返回交换内存
# sswap(total=5100273664, used=11184832512, free=-6084558848, percent=219.3, sin=0, sout=0)    

硬盘相关

  • 函数 说明
  • disk_partitions() 返回分区情况
  • disk_usage() 输入盘符,返回磁盘占用情况
  • disk_io_counters() 磁盘的读写信息
psutil.disk_usage("C:") # 查看C盘的读写情况,单位是B
# sdiskusage(total=511282507776, used=307277705216, free=204004802560, percent=60.1)

parts = psutil.disk_partitions()
for p in parts: print(p)  

打印结果如下

sdiskpart(device=‘C:\’, mountpoint=‘C:\’, fstype=‘NTFS’,opts=‘rw,fixed’, maxfile=255, maxpath=260) sdiskpart(device=‘D:\’,
mountpoint=‘D:\’, fstype=‘NTFS’, opts=‘rw,fixed’, maxfile=255, maxpath=260)

disk_io_counters函数中,perdisk为True时,返回每个磁盘的读写信息,否则返回所有磁盘相加之后的信息,示例如下

电源相关

  • 函数 返回值
  • sensors_temperatures() 温度
  • sensors_fans() 风扇转速
  • sensors_battery() 电源状态

其中CPU温度和风扇转速并不适用于Widows系统,故而下面只测试一下sensors_battery函数

psutil.sensors_battery()
sbattery(percent=100, secsleft=<BatteryTime.POWER_TIME_UNLIMITED: -2>, power_plugged=True)      

其中percent表示电池电量剩余百分比;power_plugged为True,表示电源已连接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【网络星空】

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值