A timer for timing section of code. The recommended usage is with a context manager. Example: With a context manager, the timer is started when entering and stopped at exit. With a named :class:`Timer`:: with Timer("Some costly operation"): cost
| 75 | |
| 76 | |
| 77 | class Timer: |
| 78 | """A timer for timing section of code. |
| 79 | |
| 80 | The recommended usage is with a context manager. |
| 81 | |
| 82 | Example: |
| 83 | With a context manager, the timer is started when entering |
| 84 | and stopped at exit. With a named :class:`Timer`:: |
| 85 | |
| 86 | with Timer("Some costly operation"): |
| 87 | costly_call_1() |
| 88 | costly_call_2() |
| 89 | |
| 90 | delta = timing("Some costly operation") |
| 91 | print(delta) |
| 92 | |
| 93 | or with an un-named :class:`Timer`:: |
| 94 | |
| 95 | with Timer() as t: |
| 96 | costly_call_1() |
| 97 | costly_call_2() |
| 98 | print(f"Elapsed time: {t.elapsed()}") |
| 99 | |
| 100 | Example: |
| 101 | It is possible to start and stop a timer explicitly:: |
| 102 | |
| 103 | t = Timer("Some costly operation") |
| 104 | costly_call() |
| 105 | delta = t.stop() |
| 106 | |
| 107 | and retrieve timing data using:: |
| 108 | |
| 109 | delta = t.elapsed() |
| 110 | |
| 111 | To flush the timing data for a named :class:`Timer` to the logger, |
| 112 | the timer should be stopped and flushed:: |
| 113 | |
| 114 | t.stop() |
| 115 | t.flush() |
| 116 | |
| 117 | Timings are stored globally (if task name is given) and once flushed |
| 118 | (if used without a context manager) may be printed using functions |
| 119 | :func:`timing` and :func:`list_timings`, e.g.:: |
| 120 | |
| 121 | list_timings(comm) |
| 122 | """ |
| 123 | |
| 124 | _cpp_object: _cpp.common.Timer |
| 125 | |
| 126 | def __init__(self, name: str | None = None): |
| 127 | """Create timer. |
| 128 | |
| 129 | Args: |
| 130 | name: Identifier to use when storing elapsed time in logger. |
| 131 | """ |
| 132 | self._cpp_object = _cpp.common.Timer(name) |
| 133 | |
| 134 | def __enter__(self): |