Context manager for tracking how much time is spent within context blocks. This uses `time.perf_counter` to accumulate the total amount of time in seconds in the attribute `total_time` over however many context blocks the object is used in.
| 119 | |
| 120 | |
| 121 | class PerfContext: |
| 122 | """ |
| 123 | Context manager for tracking how much time is spent within context blocks. This uses `time.perf_counter` to |
| 124 | accumulate the total amount of time in seconds in the attribute `total_time` over however many context blocks |
| 125 | the object is used in. |
| 126 | """ |
| 127 | |
| 128 | def __init__(self): |
| 129 | self.total_time: float = 0 |
| 130 | self.start_time: float | None = None |
| 131 | |
| 132 | def __enter__(self): |
| 133 | self.start_time = perf_counter() |
| 134 | return self |
| 135 | |
| 136 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 137 | if self.start_time is not None: |
| 138 | self.total_time += perf_counter() - self.start_time |
| 139 | self.start_time = None |
| 140 | |
| 141 | |
| 142 | # stores the results from profiling with trace or with other helper methods |