【Pandas实战】统计服务器CPU/GPU温度情况

在整个高中阶段的信息技术学习中,我已经做了不知道多少Pandas的题目了,不过我发现我似乎从来没用过Pandas,正好最近有这个需求,所以就趁这个机会实战了一次

起因是被我拿来做家庭服务器的Linux开发板经常自动关机,查了日志也看不出什么异常,所以我让ChatGPT写了个Python脚本记录CPU/GPU的温度情况,同时也记录了CPU占用率。

import csv
import psutil
import schedule
import time
from datetime import datetime

# Function to read temperature
def read_temp(file_path):
    try:
        with open(file_path, 'r') as file:
            temp = round(int(file.read()) / 1000.0, 2)  # Convert millidegrees Celsius to Celsius
            return temp
    except FileNotFoundError:
        return None

# Function to log CPU, GPU temperatures and CPU load
def log_temperatures_and_load():
    # Read CPU and GPU temperatures
    cpu_temp = read_temp("/sys/class/thermal/thermal_zone0/temp")
    gpu_temp = read_temp("/sys/class/thermal/thermal_zone1/temp")

    # Get CPU load (average over 1, 5, and 15 minutes)
    cpu_load = psutil.getloadavg()

    # Get the current timestamp
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    # File path to save the data
    csv_file = 'temp&load.csv'

    # Write the data to a CSV file
    with open(csv_file, mode='a', newline='') as file:
        writer = csv.writer(file)

        # Write the header if the file is empty
        if file.tell() == 0:
            writer.writerow(['Timestamp', 'CPU Temperature (°C)', 'GPU Temperature (°C)',
                             'CPU Load (1 min)'])

        # Write the temperature and CPU load data
        writer.writerow([timestamp,
                         cpu_temp if cpu_temp is not None else 'N/A',
                         gpu_temp if gpu_temp is not None else 'N/A',
                         round(cpu_load[0],2)])

    print(f"Data written to {csv_file} at {timestamp}")

schedule.every().hour.at(":00").do(log_temperatures_and_load)

print("Script started")

while True:
    schedule.run_pending()
    time.sleep(60)

运行几天后我们拿到了一个csv文件:

打开一看最后一次记录是2024/9/18 2:00,今天是9月21日,说明在9月18日凌晨开发板就已经自动关机了。截取了一部分数据如下:

纯数字的数据让人看起来很头大,所以我们使用Pandas处理数据,为了方便直观地获取结果,我选择在Jupter Notebook中编写运行代码,得益于cell的设计,代码可以分段随时运行,数据分析很方便

首先在第一个cell中,该段代码导入了Pandas以及用于画图的matplotlib

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("temp&load.csv")

此时我们运行下一个cell中的

print(df)

结果如下:

可以看到csv文件中的数据已经被成功导入进了Pandas中。

查看此DataFrame的columns:

现在我们尝试绘制CPU温度曲线图:

在该段代码中,我们以时间为X轴,CPU Temperature 为Y轴,画出了这个折线图,可以很直观的看到,在温度降到最低后,最后的温度直飙70以上,估计开发板自动关机的原因就是温度过高。

用同样的方法画出GPU温度折线图:

同样可以看到最后的温度很高。

CPU占用情况倒是一直保持在较低水平,毕竟这块板子上我也没跑什么占用CPU的程序,只有几个docker应用和这个记录数据的脚本。

接下来我们试一下统计每天的平均温度

day = []
for i in df.index:
    day.append(df.at[i, "Timestamp"][7:9])
df["Day"] = day
df.drop("Timestamp", axis = 1, inplace = True)
df1 = df.groupby("Day", as_index = False).mean()

由于原始的Timestamp是完整的时间字符串,所以需要先转换成天

df1 = df.groupby("Day", as_index = False).mean()

这行代码实现了按天分组后统计平均值

这个drop()方法我一直记不太清楚,所以我问了下AI:

In the df.drop() method in pandas, the default value of the axis parameter is 0.

When axis=0, it indicates that the operation should be performed along rows, i.e., rows will be dropped based on the labels provided.

When axis=1, it indicates that the operation should be performed along columns, i.e., columns will be dropped based on the labels provided.

If the axis parameter is not explicitly specified, the default behavior is to drop rows (axis=0).

这里注意如果没有inplace = True,Pandas不会对原始数据进行修改,要进行赋值。

df.drop("Timestamp", axis = 1, inplace = True)

可以看出每天的平均温度都在升高。

关于Pandas的实战到这里就已经结束了,开发板自动关机的原因基本确定是温度过高导致的,不过目前来说并没有很好的解决方案,毕竟我都上了散热风扇了,温度还是会在长时间运行后变得很高。

如何问题解决,估计会再写一篇blog记录的。

本文作者: undefined
文章标题:【Pandas实战】统计服务器CPU/GPU温度情况
本文地址:https://blog.xuxiny.top/index.php/2024/09/21/986/
版权说明:若无注明,本文均由undefined原创,转载请保留文章出处。

评论

  1. 2 周前
    2024-10-04 20:12:32

    你好主播,很抱歉通过文章评论的形式通知你,今天翻贵站的时候发现nav.xuxiny.top的SSL证书已过期三天,希望能续期一下,很好的作品👍
    (国庆节快乐呀|´・ω・)ノ)

    • 博主
      是路明呀
      2 周前
      2024-10-06 23:02:53

      您好,SSL证书已经续签好了,感谢您的提醒!

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇