Skip to content

Latest commit

 

History

History
62 lines (43 loc) · 2.07 KB

File metadata and controls

62 lines (43 loc) · 2.07 KB

Performance and Profiling Basics (Python)

This module introduces simple timing and allocation-aware optimization patterns in Python.

Learning Metadata

  • Difficulty: Advanced.
  • Estimated Time: 45-60 minutes.
  • Prerequisites: 02-core/algorithms-basics, 03-advanced/structs-and-classes.
  • Cross-Language Lens: Compare timing tools, allocation costs, and how each runtime changes the meaning of fast enough.

Quick Run

python example/main.py

Topics Covered

  • Measuring elapsed time with time.perf_counter.
  • Comparing two implementations on the same workload.
  • Reducing temporary allocations with str.join.
  • Pre-sizing mutable containers when the final size is known.

Common Pitfalls

  • Timing workloads that are too small to compare fairly.
  • Measuring setup work along with the code you meant to test.
  • Drawing conclusions from one noisy run.
  • Optimizing before understanding the dominant cost.

Cross-Language Notes

  • Python makes performance differences easier to observe at a high level, but lower-level costs are hidden compared with C++ or Go.
  • Compared with C# and TypeScript, small code-shape changes can matter less than algorithmic choice and object overhead.
  • The cross-language lesson is to measure honestly before assuming a slower runtime makes an idea unimportant.

Exercise Focus

  • exercises/01.py: compare string concatenation with str.join.
  • exercises/02.py: compare list growth with and without pre-sized storage.

Exercise Specs

  1. exercises/01.py
  • Input: line count.
  • Output: elapsed seconds for both string-building approaches.
  • Edge cases: zero lines; very small workloads produce noisy timings.
  1. exercises/02.py
  • Input: element count.
  • Output: elapsed seconds for list fill with and without pre-sized storage.
  • Edge cases: zero count; small sizes with little visible difference.

Checkpoint

  • I can measure code with time.perf_counter.
  • I can compare two implementations on the same input.
  • I can explain why fewer allocations can help.
  • I completed exercises/01.py.
  • I completed exercises/02.py.