-
-
Save bhuiyanmobasshir94/8676e681eb30f0c34f2c8e977539e886 to your computer and use it in GitHub Desktop.
Profile CPU usage in Python using psutil.
This file contains hidden or 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