3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NVIDIA GPUの温度をPythonで取得する方法

Last updated at Posted at 2025-12-01

NVIDIA GPUの温度はタスクマネージャーやWeights & Biasesなどから確認することができますが、Pythonスクリプトで取得したいことがあります。例えば、一定温度を超えた場合は10minスリープさせる、あるいは緊急停止するなどの用途を想定しています。
この記事では、NVIDIA GPUの温度をPythonで取得する3つの方法を紹介します。

方法①:pyNVMLを使う

NVIDIA公式のpyNVML(Python bindings to the NVIDIA Management Library)を使う方法です。公式ライブラリならではの安心感があります。特段理由がなければ、こちらの方法①をオススメします。

pip install nvidia-ml-py
import pynvml

pynvml.nvmlInit()

device_count = pynvml.nvmlDeviceGetCount()

for i in range(device_count):
    handle = pynvml.nvmlDeviceGetHandleByIndex(i)
    name = pynvml.nvmlDeviceGetName(handle)
    temp = pynvml.nvmlDeviceGetTemperature(handle, pynvml.NVML_TEMPERATURE_GPU)

    print(f"GPU {i} ({name}): {temp}°C")

pynvml.nvmlShutdown()
GPU 0 (NVIDIA GeForce RTX 5090): 49°C

方法②:GPUtilを使う方法

GPUtilはnvidia-smiを使用してNVIDA GPUからGPUの情報を取得するためのサードパーティライブラリです。開発が2018年12月に終了していますが、シンプルで使いやすいメリットがあります。nvidia-smiのインターフェースは安定しているため、現在でも問題なく使用できます。

pip install gputil
import GPUtil

# 全GPUの情報を取得
gpus = GPUtil.getGPUs()

for gpu in gpus:
    print(f"GPU {gpu.id}: {gpu.name}")
    print(f"  温度: {gpu.temperature}°C")
    print(f"  使用率: {gpu.load * 100}%")
    print(f"  メモリ使用: {gpu.memoryUsed}MB / {gpu.memoryTotal}MB")
GPU 0: NVIDIA GeForce RTX 5090
  温度: 49.0°C
  使用率: 99.0%
  メモリ使用: 31906.0MB / 32607.0MB

方法③:nvidia-smi + サブプロセス

nvidia-smiをサブプロセスで呼び出す方法です。方法①、②とは異なり、外部ライブラリを使わないメリットがあります。

import subprocess


def get_nvidia_gpu_temp_smi() -> float:
    """nvidia-smiコマンドを使ってNVIDIA GPUの温度を取得する"""
    temps = []

    # 温度を取得するコマンド
    command = [
        "nvidia-smi",
        "--query-gpu=temperature.gpu",
        "--format=csv,noheader,nounits"
    ]
    # コマンドを実行し、標準出力を取得
    result = subprocess.run(command, capture_output=True, text=True, check=True, encoding='utf-8')
    output = result.stdout.strip()

    # 出力を行ごとに分割し変換
    temps = [float(temp) for temp in output.splitlines()]
    return sum(temps) / len(temps)


if __name__ == "__main__":
    gpu_temperature = get_nvidia_gpu_temp_smi()
    print(f"{gpu_temperature}°C")
49.0°C
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?