Periodically samples CPU and memory usage of a process given its pid. These measurements are sampled until the process is no longer running.
| 209 | |
| 210 | |
| 211 | class ProcessBenchmarker: |
| 212 | """ |
| 213 | Periodically samples CPU and memory usage of a process given its pid. |
| 214 | These measurements are sampled until the process is no longer running. |
| 215 | """ |
| 216 | |
| 217 | def benchmark_process(self, pid, data_interval): |
| 218 | parent_pid = os.getpid() |
| 219 | try: |
| 220 | # Benchmark the process where the script is being run. |
| 221 | return self._run_benchmark(pid, data_interval) |
| 222 | except KeyboardInterrupt: |
| 223 | # If there is an interrupt, then try to clean everything up. |
| 224 | proc = psutil.Process(parent_pid) |
| 225 | procs = proc.children(recursive=True) |
| 226 | |
| 227 | for child in procs: |
| 228 | child.terminate() |
| 229 | |
| 230 | gone, alive = psutil.wait_procs(procs, timeout=1) |
| 231 | for child in alive: |
| 232 | child.kill() |
| 233 | raise |
| 234 | |
| 235 | def _run_benchmark(self, pid, data_interval): |
| 236 | process_to_measure = psutil.Process(pid) |
| 237 | samples = [] |
| 238 | |
| 239 | while process_to_measure.is_running(): |
| 240 | if process_to_measure.status() == psutil.STATUS_ZOMBIE: |
| 241 | break |
| 242 | time.sleep(data_interval) |
| 243 | try: |
| 244 | # Collect the memory and cpu usage. |
| 245 | memory_used = process_to_measure.memory_info().rss |
| 246 | cpu_percent = process_to_measure.cpu_percent() |
| 247 | except ( |
| 248 | psutil.AccessDenied, |
| 249 | psutil.ZombieProcess, |
| 250 | psutil.NoSuchProcess, |
| 251 | ): |
| 252 | # Trying to get process information from a closed or |
| 253 | # zombie process will result in corresponding exceptions. |
| 254 | break |
| 255 | # Determine the lapsed time for bookkeeping |
| 256 | current_time = time.time() |
| 257 | samples.append( |
| 258 | { |
| 259 | "time": current_time, |
| 260 | "memory": memory_used, |
| 261 | "cpu": cpu_percent, |
| 262 | } |
| 263 | ) |
| 264 | return samples |
| 265 | |
| 266 | |
| 267 | class BenchmarkHarness: |