Measure and track the wall and CPU time of defined scopes in Python.
It's suitable for long-running applications which should be monitored.
$ pip install tic-toc
The following examples demonstrate the most simple usage:
Here you see the implicit variant with the with
construct:
from tic_toc import Timer
with Timer('NAME') as timer:
print('Scope: ' + timer.name)
time.sleep(1)
Here you see the explicit variant without the with
construct:
from tic_toc import Timer
timer = Timer('NAME')
timer.tic() # or .start()
print('Scope: ' + timer.name)
time.sleep(1)
timer.toc() # or .end()
The outputs are similar to each other:
# > NAME ...
# Scope: NAME
# < NAME [WALL: 1.0034s] [CPU: 0.0001s]
You can find more extended examples (e.g. with logging
, tqdm
or pandas
) in the examples directory.
class Timer(object):
def __init__(self, name: str = None,
format_start: str = '> {name} ...',
format_end: str = '< {name} [WALL: {time_wall:.4f}s] [CPU: {time_cpu:.4f}s]',
to: Callable[[Any], None] = lambda msg: print(msg)):
name
: str, optional, default: leading hash with four random digits, eg.#0512
format_start
: str, optional, default:'> {name} ...'
format_end
: str, optional, default:'< {name} [WALL: {time_wall:.4f}s] [CPU: {time_cpu:.4f}s]'
to
:Callable[[Any], None]
, optional, default:lambda msg: print(msg)
You can change the visual string formats and the output method.
- Answer by Eli Bendersky to the question 'tic, toc functions analog in Python'
- Python Clocks Explained by Nat Dunn
- Python 3.7 perf_counter() nanoseconds by Victor Stinner
- PEP 564: New Time Functions With Nanosecond Resolution
- PEP 560: Core Support for typing module and Generic Types
- Slow and fast methods for generating random integers in Python by Eli Bendersky
The module is Open Source Software released under the MIT license.