3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonコード内で確認したい

topコマンドでも確認できますが、コード内で監視したい場合、次のようにします。

import psutil

cpu_percent = psutil.cpu_percent(percpu=True)
mem = psutil.virtual_memory() 

print('cpu: ',cpu_percent)
print('memory: ',mem)

cpu: 51.4000 55.5000
memory: 17.9

一定の時間間隔で監視する場合は、

import psutil
import threading
import time

def monitor_cpu(initial_time,event):
    print("START monitor_cpu")
    while not event.wait(0.1):
        elapsed_time = time.time() - initial_time
        cpu_percent = psutil.cpu_percent(percpu=True)
        mem = psutil.virtual_memory() 

        cpu_percent = '\t'.join(["{:10.4f}".format(v) for v in cpu_percent])
        print("time:", int(elapsed_time))
        print("cpu: ", cpu_percent)
        print("memory: ", mem.percent)
    print("END monitor_cpu")
event = threading.Event()
initial_time = time.time()
m = threading.Thread(target=monitor_cpu,args=((initial_time,event)))
m.start() # 開始
tmp = 0

# 監視したい処理

event.set() # 終了

START monitor_cpu
time: 0.16
cpu: 51.4000 55.5000
memory: 17.9
time: 1.84
cpu: 0.0000 90.9000
memory: 17.9
time: 1.95
cpu: 100.0000 9.1000
memory: 17.9
...
...

マルチCPUは、CPUごとの使用率が返されます。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

機械学習、ARアプリ(Web/iOS)を作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium
GitHub

3
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?