Skip to content

Instantly share code, notes, and snippets.

@bhuiyanmobasshir94
Forked from rkaneko/print_cpu_usage.py
Last active April 28, 2023 02:40
Show Gist options
  • Save bhuiyanmobasshir94/8676e681eb30f0c34f2c8e977539e886 to your computer and use it in GitHub Desktop.
Save bhuiyanmobasshir94/8676e681eb30f0c34f2c8e977539e886 to your computer and use it in GitHub Desktop.
Profile CPU usage in Python using psutil.
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