Codetiming

1.4.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

Demonstrates `codetiming.Timer` used as a class, a context manager, and a decorator. It also shows how to access accumulated statistics for named timers.

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()}")

view raw JSON →