【Python】コンピュータの情報取得

Pythonでコンピュータの情報を取得する方法について入門者向けにまとめました。

## 【情報取得】OS名、CPU・メモリの使用率、プロセス一覧

Python標準モジュール「platform」のplatform.system()で実行中プラットフォーム名を取得できます。

# -*- coding:utf-8 -*-
import platform

# システムの種類を取得
systype = platform.system()

# 取得した情報を表示
print(systype) # Windows

これを応用すれば、実行するプラットフォームによって、プログラムの処理を変えたりできます。

関連記事
1 【Python】利用中のOS名を取得

Pythonモジュール「psutil」でCPUやメモリの利用情報を取得できます。

# -*- coding:utf-8 -*-
import psutil

# メモリとCPUの利用情報を取得
memory = psutil.virtual_memory()
cpu_percent = psutil.cpu_percent(interval=1)

print('メモリ使用率:', memory.percent) # メモリ使用率: 60.0
print('CPU使用率:', cpu_percent) # CPU使用率 2.4
関連記事
1 【Python/psutil】CPUやメモリの使用率を取得

Python標準モジュール「subprocess」でWindowsタスクマネージャーのプロセスから、メモリの使用量を取得できます。

# -*- coding:utf-8 -*-
import subprocess

# タスクマネージャーのプロセルを取得
proc = subprocess.Popen('tasklist', shell=True, stdout=subprocess.PIPE)

# 1行ずつ表示
for line in proc.stdout:
    print(line.decode('shift-jis'))

"""
イメージ名                     PID セッション名     セッション# メモリ使用量
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0          8 K
System                           4 Services                   0     13,104 K
Registry                        96 Services                   0     22,876 K
smss.exe                       360 Services                   0        452 K
csrss.exe                      512 Services                   0      1,864 K
:
"""
関連記事
1 【Python】Windowsタスクマネージャーのプロセスを表示

## 【計測】プログラムの処理時間

Pythonでは、標準モジュールtimeを使うことで時間を取得できます。
処理時間を計測するには、以下の計算を行います。

処理時間=(処理終了時間)-(処理開始時間)

time.time

time.time()を使った測定方法です。
ただし、この方法では1/60秒の精度しか出ないようです。

# -*- coding: utf-8
import time

def main():
    # 開始時間
    start = time.time()

    # 計測する処理
    i = 0
    for i in range(100000):
        i = i * 2

    # 終了時間
    end = time.time()

    # 処理時間=終了時間-開始時間
    print (end-start) # 0.03652310371398926[秒]


if __name__ == '__main__':
        main()

time.perf_counter

time.perf_counter()を使った測定方法です。
こちらのほうが測定精度は高いようです。

# -*- coding: utf-8
import time

# 開始時間
start = time.perf_counter()

# 計測する処理
i = 0
for i in range(100000):
    i = i * 2

# 終了時間
end = time.perf_counter()

# 処理時間=終了時間-開始時間
print (end-start) # 0.015586701192719541[秒]
関連記事
1 【Python入門】サンプル集
2 【Python】日時データの処理(datetime)
Python
スポンサーリンク

コメント