-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfps.py
executable file
·61 lines (53 loc) · 2.19 KB
/
fps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from pathlib import Path
import datetime
import json
import logging
import os
import time
logger = logging.getLogger(__name__)
class FpsDisplay:
"""Context manager that displays an EMA average of the FPS periodically.
Example usage:
fps = FpsDisplay()
while True:
with fps:
img = grabber.grab()
process_image(img)
"""
def __init__(self, ema_alpha:float=0.1, display_every_secs:float=1.0, catch_exceptions:bool=False, status_file:Path=None):
self.last_msg_time = time.monotonic()
self.ema_fps = 0
self.ema_alpha = ema_alpha
self.display_every_secs = display_every_secs
self.catch_exceptions = catch_exceptions
self.exception_delay = 5.0
self.status_file = status_file
def __enter__(self):
self.start_time = time.monotonic()
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.catch_exceptions and exc_type is not None:
if issubclass(exc_type, KeyboardInterrupt):
raise
logger.error(f"Exception {exc_type.__name__}: {exc_value}. Pausing for {self.exception_delay} seconds before continuing.", exc_info=(exc_type, exc_value, traceback))
# TODO: Maybe some kind of backoff?
time.sleep(self.exception_delay)
return True # Prevent the exception from being propagated
elapsed = time.monotonic() - self.start_time
self.tick(elapsed)
def tick(self, elapsed:float):
current_fps = 1.0 / elapsed
if self.ema_fps == 0:
self.ema_fps = current_fps
else:
self.ema_fps = self.ema_alpha * current_fps + (1 - self.ema_alpha) * self.ema_fps
if time.monotonic() - self.last_msg_time >= self.display_every_secs:
logger.info(f"average recent fps={self.ema_fps:.2f}")
self.last_msg_time = time.monotonic()
if self.status_file:
doc = {
"fps": self.ema_fps,
"timestamp": datetime.datetime.now().isoformat(),
"pid": os.getpid(),
}
self.status_file.write_text(json.dumps(doc))