Python Debugging Cheat Sheet/Time a block of code

Measure elapsed time around suspicious code paths.

Section: Logging and Diagnostics

Time a block of code

python
python
import time

start = time.perf_counter()
result = expensive_call()
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.4f}s")

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Logging and Diagnostics
Enable basic debug logging
Turn on debug-level logs quickly.
OpenIn sheetpythonsame section
Use a readable log format
Add timestamps and levels to logs.
OpenIn sheetpythonsame section
Log an exception with traceback
Emit the stack trace automatically in an except block.
OpenIn sheetpythonsame section
Attach request or job context to logs
Add contextual identifiers that make debugging easier.
OpenIn sheetpythonsame section
Benchmark small snippets with timeit
Measure a small expression from the command line.
OpenIn sheetbashsame section
Sort cProfile output by total time
Surface slow functions first.
OpenIn sheetbash1 tag match