Skip to content

Commit

Permalink
Delay only once for all processes when measuring cpu usage
Browse files Browse the repository at this point in the history
  • Loading branch information
tysmith committed May 8, 2024
1 parent b753ab9 commit b3c1feb
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
20 changes: 18 additions & 2 deletions src/ffpuppet/process_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from logging import getLogger
from platform import system
from subprocess import Popen
from time import sleep
from typing import Generator, List, Optional, Tuple

from psutil import AccessDenied, NoSuchProcess, Process, TimeoutExpired, wait_procs
Expand Down Expand Up @@ -36,15 +37,30 @@ def __init__(self, proc: "Popen[bytes]") -> None:
def cpu_usage(self) -> Generator[Tuple[int, float], None, None]:
"""Collect percentage of CPU usage per process.
Note: the returned value can be > 100.0 in case of a process running multiple
threads on different CPU cores.
See: https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_percent
This value is not divided by CPU count because we are typically more concerned
with the low end for detecting idle processes.
Args:
None
Yields:
PID and the CPU usage as a percentage.
"""
for proc in self.processes():
procs = self.processes()
for proc in procs:
try:
proc.cpu_percent()
except (AccessDenied, NoSuchProcess): # pragma: no cover
continue
# psutil recommends at least '0.1'.
sleep(0.1)
for proc in procs:
try:
yield proc.pid, proc.cpu_percent(interval=0.1)
yield proc.pid, proc.cpu_percent()
except (AccessDenied, NoSuchProcess): # pragma: no cover
continue

Expand Down
1 change: 0 additions & 1 deletion src/ffpuppet/test_ffpuppet.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,7 +755,6 @@ def test_ffpuppet_27():
ffp.launch(TESTFF_BIN, location=srv.get_addr())
usage = next(ffp.cpu_usage())
assert usage
assert usage[1] <= 100
assert usage[1] >= 0
ffp.close()
assert ffp.wait(timeout=10)
Expand Down
2 changes: 2 additions & 0 deletions src/ffpuppet/test_process_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ def test_process_tree_01(tmp_path, enable_launcher, launcher_is_parent):
assert tree.is_running()
assert len(tree.processes()) == expected_procs
assert tree.wait_procs() == expected_procs
usage = tuple(tree.cpu_usage())
assert len(usage) == expected_procs
tree.terminate()
finally:
# this should cause everything to close gracefully if it is still running
Expand Down

0 comments on commit b3c1feb

Please sign in to comment.