Skip to content

Instantly share code, notes, and snippets.

@rkaneko
Created February 18, 2020 04:29
Show Gist options
  • Save rkaneko/bca4ed436affa5f7d020dd2a8db44af5 to your computer and use it in GitHub Desktop.
Save rkaneko/bca4ed436affa5f7d020dd2a8db44af5 to your computer and use it in GitHub Desktop.
Profile CPU usage in Python sing 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