Skip to main content

Tiny, friendly timing utilities for Python code blocks and functions.

Project description

⏱️ smarttimer

PyPI version Python 3.8+ License: MIT

Tiny, friendly timing utilities for Python code blocks and functions. Perfect for quick performance checks and micro-benchmarks.

🚀 Install

pip install py-smarttimer

📖 Quick Start

from smarttimer import time_block, benchmark, measure, compare

🎯 Features

⏲️ Time any code block

from smarttimer import time_block

with time_block("data processing"):
    df = pd.read_csv("large_file.csv")
    result = df.groupby("category").sum()
[smarttimer] data processing took 2.3451s

🎪 Benchmark functions with a decorator

from smarttimer import benchmark

@benchmark
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

result = fibonacci(30)  # Automatically prints timing

📊 Measure with statistics

from smarttimer import measure

def matrix_multiply(a, b):
    return [[sum(x*y for x,y in zip(row,col)) for col in zip(*b)] for row in a]

# Run 10 times with 2 warmup runs
result, elapsed = measure(
    matrix_multiply,
    [[1,2],[3,4]], [[5,6],[7,8]],
    repeats=10,
    warmup=2
)

🏁 Compare multiple functions

from smarttimer import compare

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# Compare performance
data = [64, 34, 25, 12, 22, 11, 90]
compare(bubble_sort, quick_sort, args=(data.copy(),), repeats=100)
[smarttimer] Function comparison (100 runs):
  quick_sort: 0.000012s ± 0.000003s (fastest)
  bubble_sort: 0.000089s ± 0.000012s (7.4x slower)

🔍 Silent timing for custom logic

from smarttimer import TimingContext

with TimingContext() as timer:
    expensive_computation()

if timer.elapsed > 1.0:
    print(f"Slow operation detected: {timer.elapsed:.2f}s")

💾 Memory profiling (optional)

from smarttimer import profile_memory

@profile_memory
def load_large_dataset():
    return [i**2 for i in range(1_000_000)]

data = load_large_dataset()
[smarttimer] load_large_dataset took 0.1234s, memory: 45.2MB → 82.1MB (+36.9MB)

Requires pip install psutil for memory profiling

🛠️ Advanced Usage

Disable timing conditionally

DEBUG = False

with time_block("debug operation", enabled=DEBUG):
    debug_heavy_computation()  # Only timed when DEBUG=True

Custom output and precision

import sys
from smarttimer import benchmark

@benchmark(precision=6, output=sys.stderr)
def precise_operation():
    return sum(i**0.5 for i in range(10000))

Warmup runs for accurate benchmarks

# Skip first 3 runs to avoid cold start effects
result, time_taken = measure(
    compiled_function,
    args,
    repeats=20,
    warmup=3
)

🎨 Why smarttimer?

  • Zero dependencies (except optional psutil for memory profiling)
  • Minimal overhead - uses time.perf_counter() for precision
  • Flexible - works as context manager, decorator, or function
  • Clean output - consistent, readable timing reports
  • Production ready - disable timing in production with enabled=False

📦 API Reference

Function Purpose Returns
time_block(name) Time a code block Context manager
@benchmark Time a function call Decorated function
measure(func, *args, repeats=1) Benchmark with repeats (result, elapsed)
compare(*funcs, args=(), repeats=5) Compare functions Statistics dict
TimingContext() Silent timing Context with .elapsed
@profile_memory Time + memory usage Decorated function

🤝 Contributing

Found a bug? Want a feature? Open an issue or submit a PR!

📄 License

MIT License - see LICENSE file for details.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_smarttimer-0.1.0.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_smarttimer-0.1.0-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file py_smarttimer-0.1.0.tar.gz.

File metadata

  • Download URL: py_smarttimer-0.1.0.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.6

File hashes

Hashes for py_smarttimer-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b3eb350a54adcc33636127e995f036a150c6177d83d63b68b52fc2a2bebcbdcc
MD5 40be1385d8362ce012a6021e00b0cfe0
BLAKE2b-256 6f4faad1bf01ea5eecd1ad354de2c8dca3669bde11315d2d8af0ca3a09e0bec2

See more details on using hashes here.

File details

Details for the file py_smarttimer-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: py_smarttimer-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.6

File hashes

Hashes for py_smarttimer-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5a3388c38db22fec70e0be8feec29f3a29bd2e8199ef77d7157b13fd323caf08
MD5 557e6252931fb2935c8ed78463fc3613
BLAKE2b-256 4ee6157556632adeb61b60611fe2cbe12c1686a1bc8007e62a81ef904339b898

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page