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_times
和cpu_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,表示电源已连接。