1
1

More than 1 year has passed since last update.

RadeonとかのGPU使用率を取得(Python)

Last updated at Posted at 2021-12-12

誰かに使えるわけでもない、そんな記事です。
自分へのメモ用に…

はじめに

ふと、RadeonとかのGPU使用率ってどうやって取るんだ?という疑問をもった
Radeonソフトとか、パフォーマンスモニター、タスクマネージャーを使うとできるんだけど、それを数値で取得したいなぁと思った
というのは、ちょうど、モニタリングアプリケーションを作っていた

ので、なんか最後にpythonでできないかなーと思い、いろいろ調べてみた。

すると、stackoverflowとかでそれっぽいのを発見
- https://stackoverflow.com/questions/56830434/c-sharp-get-total-usage-of-gpu-in-percentage
- https://superuser.com/questions/1632758/how-to-get-gpu-usage-and-gpu-memory-info-of-a-process-by-powershell7

お、できそうだ。やってみよう。

コード

pythonnetでPerformanceCounterCategoryPerformanceCounterListを引っ張ってきます。
Listを引っ張ってくるのは、pythonのlistより若干処理が速いためです。
「C#でよくね?」と思った方、その通りです

こんな感じで取得できます。

import re
import clr
import time

clr.AddReference('System.Diagnostics.Process')
clr.AddReference('System.Collections')

import System.Diagnostics as Diagnostics # type: ignore
from System.Collections.Generic import List # type: ignore

GPU_Engines = None

def get_process_counter() -> List:
    category = Diagnostics.PerformanceCounterCategory('GPU Engine')
    ret = List[Diagnostics.PerformanceCounter]()

    for cat_name in category.GetInstanceNames():
        if re.findall(r'engtype_3D', cat_name):
            ret.Add(category.GetCounters(cat_name)[-1])

    return ret

def gpu_usage() -> float:
    global GPU_Engines
    if GPU_Engines is None:
        GPU_Engines = get_process_counter()
        _ = [x.NextValue() for x in GPU_Engines]
        time.sleep(1)

    return sum(gpu.NextValue() for gpu in GPU_Engines)


if __name__ == '__main__':
    print(gpu_usage())
    time.sleep(1)
    print(gpu_usage())

gpu_usage()を呼び出すと使用率を表示してくれます。初回だけ、PerformanceCounterの関係上、初期化でsleepしているので遅いです。それ以降はすぐに出してくれます。

1
1
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
1
1