Windows利用Python和定时器等库,自动定时获取CPU的负载、温度、内存占用等信息,定时间隔2秒,采集1000个样本数据,分别写入CSV、Excel文件中。调用pandas、matplotlib等库,对数据进行分析、绘制时间图。
时间: 2024-05-31 07:08:35 浏览: 141
以下是Python代码实现:
```python
import psutil
import time
import csv
import openpyxl
import pandas as pd
import matplotlib.pyplot as plt
# 获取CPU负载、温度、内存占用等信息
def get_cpu_info():
cpu_percent = psutil.cpu_percent()
cpu_temp = psutil.sensors_temperatures().get('coretemp')[0].current
mem_percent = psutil.virtual_memory().percent
return cpu_percent, cpu_temp, mem_percent
# 写入CSV文件
def write_csv(data):
with open('cpu_info.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(data)
# 写入Excel文件
def write_excel(data):
wb = openpyxl.load_workbook('cpu_info.xlsx')
sheet = wb.active
sheet.append(data)
wb.save('cpu_info.xlsx')
# 采集1000个样本数据,每隔2秒采集一次
for i in range(1000):
cpu_percent, cpu_temp, mem_percent = get_cpu_info()
current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
# 写入CSV文件
write_csv([current_time, cpu_percent, cpu_temp, mem_percent])
# 写入Excel文件
write_excel([current_time, cpu_percent, cpu_temp, mem_percent])
time.sleep(2)
# 读取CSV文件并绘制时间图
data = pd.read_csv('cpu_info.csv', header=None)
data.columns = ['time', 'cpu_percent', 'cpu_temp', 'mem_percent']
data['time'] = pd.to_datetime(data['time'])
data = data.set_index('time')
data.plot(figsize=(10, 5))
plt.title('CPU Info')
plt.xlabel('Time')
plt.ylabel('Percentage/℃')
plt.show()
```
以上代码会生成两个文件:`cpu_info.csv`和`cpu_info.xlsx`,分别用于存储采集的数据。然后,读取CSV文件并使用pandas和matplotlib库对数据进行分析和绘图。绘制结果如下:
![CPU Info](https://i.imgur.com/5Dt5nZd.png)
阅读全文