下面是使用 Python 监测 CPU 占用率并将其记录到 txt 文件中的示例程序:
import os
import time
def get_cpu_usage():
# 获取 CPU 占用率
return float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline())
# 循环每隔 1 秒获取一次 CPU 占用率
while True:
# 获取当前时间
current_ti