Codetiming
Codetiming is a flexible and customizable Python library for timing code execution. It allows users to measure the performance of different code blocks, functions, or entire scripts using a simple `Timer` class, context manager, or decorator. The current version is 1.4.0, and releases are made on an as-needed basis.
Warnings
- breaking Explicit support for Python 3.6 was dropped in version 1.4.0. Users on Python 3.6 should pin their `codetiming` dependency to `<1.4.0`.
- gotcha When using `Timer` as a decorator on `async` functions, the reported time might be 0 or incorrect. This is a known open issue.
- gotcha The `text` argument for `Timer` is not an f-string. If you want to include f-string-like formatting (e.g., a variable from the current scope) within the `text` string, you must use double curly braces to escape the parts that `codetiming` will format.
- gotcha Named timers accumulate elapsed time across multiple uses. If you reuse a `Timer` instance or a name for `Timer` and expect a fresh measurement, you need to manually reset or manage these timings (e.g., retrieve statistics and then delete the timer from `Timer.timers`).
Install
-
pip install codetiming
Imports
- Timer
from codetiming import Timer
Quickstart
from codetiming import Timer
import time
# As a class
t = Timer(name="class method")
t.start()
time.sleep(0.01)
t.stop()
# As a context manager
with Timer(name="context manager"):
time.sleep(0.02)
# As a decorator
@Timer(name="decorator")
def my_function():
time.sleep(0.03)
my_function()
# Accessing accumulated times for named timers
print(f"Total time for 'class method': {Timer.timers.total('class method'):.4f} seconds")
print(f"All named timers: {Timer.timers.items()}")