Created
February 18, 2020 04:29
-
-
Save rkaneko/bca4ed436affa5f7d020dd2a8db44af5 to your computer and use it in GitHub Desktop.
Profile CPU usage in Python sing psutil.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import multiprocessing as mp | |
import psutil | |
from typing import Any, Callable, List, Tuple | |
def monitor(target: Callable[..., Any], args: Tuple[Any, ...]) -> List[float]: | |
worker_process = mp.Process(target=target, args=args) | |
worker_process.start() | |
p = psutil.Process(worker_process.pid) | |
cpu_percents = [] | |
while worker_process.is_alive(): | |
cpu_percents.append(p.cpu_percent()) | |
time.sleep(0.01) | |
worker_process.join() | |
return cpu_percents | |
def profile() -> None: | |
target = lambda x: x + 1 | |
args = (1,) | |
cpu_percents = monitor(target, args) | |
for i, cpu_percent in enumerate(cpu_percents): | |
print(f"[{i}]: {cpu_percent}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment