Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Part of a 72-plugin marketplace with 112 AI agents and 146 skills for Claude Code development automation.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/details.md
1# python-performance-optimization — detailed patterns and worked examples23## Profiling Tools45### Pattern 1: cProfile - CPU Profiling67```python8import cProfile9import pstats10from pstats import SortKey1112def slow_function():13"""Function to profile."""14total = 015for i in range(1000000):16total += i17return total1819def another_function():20"""Another function."""21return [i**2 for i in range(100000)]2223def main():24"""Main function to profile."""25result1 = slow_function()26result2 = another_function()27return result1, result22829# Profile the code30if __name__ == "__main__":31profiler = cProfile.Profile()32profiler.enable()3334main()3536profiler.disable()3738# Print stats39stats = pstats.Stats(profiler)40stats.sort_stats(SortKey.CUMULATIVE)41stats.print_stats(10) # Top 10 functions4243# Save to file for later analysis44stats.dump_stats("profile_output.prof")45```4647**Command-line profiling:**4849```bash50# Profile a script51python -m cProfile -o output.prof script.py5253# View results54python -m pstats output.prof55# In pstats:56# sort cumtime57# stats 1058```5960### Pattern 2: line_profiler - Line-by-Line Profiling6162```python63# Install: pip install line-profiler6465# Add @profile decorator (line_profiler provides this)66@profile67def process_data(data):68"""Process data with line profiling."""69result = []70for item in data:71processed = item * 272result.append(processed)73return result7475# Run with:76# kernprof -l -v script.py77```7879**Manual line profiling:**8081```python82from line_profiler import LineProfiler8384def process_data(data):85"""Function to profile."""86result = []87for item in data:88processed = item * 289result.append(processed)90return result9192if __name__ == "__main__":93lp = LineProfiler()94lp.add_function(process_data)9596data = list(range(100000))9798lp_wrapper = lp(process_data)99lp_wrapper(data)100101lp.print_stats()102```103104### Pattern 3: memory_profiler - Memory Usage105106```python107# Install: pip install memory-profiler108109from memory_profiler import profile110111@profile112def memory_intensive():113"""Function that uses lots of memory."""114# Create large list115big_list = [i for i in range(1000000)]116117# Create large dict118big_dict = {i: i**2 for i in range(100000)}119120# Process data121result = sum(big_list)122123return result124125if __name__ == "__main__":126memory_intensive()127128# Run with:129# python -m memory_profiler script.py130```131132### Pattern 4: py-spy - Production Profiling133134```bash135# Install: pip install py-spy136137# Profile a running Python process138py-spy top --pid 12345139140# Generate flamegraph141py-spy record -o profile.svg --pid 12345142143# Profile a script144py-spy record -o profile.svg -- python script.py145146# Dump current call stack147py-spy dump --pid 12345148```149150## Optimization Patterns151152### Pattern 5: List Comprehensions vs Loops153154```python155import timeit156157# Slow: Traditional loop158def slow_squares(n):159"""Create list of squares using loop."""160result = []161for i in range(n):162result.append(i**2)163return result164165# Fast: List comprehension166def fast_squares(n):167"""Create list of squares using comprehension."""168return [i**2 for i in range(n)]169170# Benchmark171n = 100000172173slow_time = timeit.timeit(lambda: slow_squares(n), number=100)174fast_time = timeit.timeit(lambda: fast_squares(n), number=100)175176print(f"Loop: {slow_time:.4f}s")177print(f"Comprehension: {fast_time:.4f}s")178print(f"Speedup: {slow_time/fast_time:.2f}x")179180# Even faster for simple operations: map181def faster_squares(n):182"""Use map for even better performance."""183return list(map(lambda x: x**2, range(n)))184```185186### Pattern 6: Generator Expressions for Memory187188```python189import sys190191def list_approach():192"""Memory-intensive list."""193data = [i**2 for i in range(1000000)]194return sum(data)195196def generator_approach():197"""Memory-efficient generator."""198data = (i**2 for i in range(1000000))199return sum(data)200201# Memory comparison202list_data = [i for i in range(1000000)]203gen_data = (i for i in range(1000000))204205print(f"List size: {sys.getsizeof(list_data)} bytes")206print(f"Generator size: {sys.getsizeof(gen_data)} bytes")207208# Generators use constant memory regardless of size209```210211### Pattern 7: String Concatenation212213```python214import timeit215216def slow_concat(items):217"""Slow string concatenation."""218result = ""219for item in items:220result += str(item)221return result222223def fast_concat(items):224"""Fast string concatenation with join."""225return "".join(str(item) for item in items)226227def faster_concat(items):228"""Even faster with list."""229parts = [str(item) for item in items]230return "".join(parts)231232items = list(range(10000))233234# Benchmark235slow = timeit.timeit(lambda: slow_concat(items), number=100)236fast = timeit.timeit(lambda: fast_concat(items), number=100)237faster = timeit.timeit(lambda: faster_concat(items), number=100)238239print(f"Concatenation (+): {slow:.4f}s")240print(f"Join (generator): {fast:.4f}s")241print(f"Join (list): {faster:.4f}s")242```243244### Pattern 8: Dictionary Lookups vs List Searches245246```python247import timeit248249# Create test data250size = 10000251items = list(range(size))252lookup_dict = {i: i for i in range(size)}253254def list_search(items, target):255"""O(n) search in list."""256return target in items257258def dict_search(lookup_dict, target):259"""O(1) search in dict."""260return target in lookup_dict261262target = size - 1 # Worst case for list263264# Benchmark265list_time = timeit.timeit(266lambda: list_search(items, target),267number=1000268)269dict_time = timeit.timeit(270lambda: dict_search(lookup_dict, target),271number=1000272)273274print(f"List search: {list_time:.6f}s")275print(f"Dict search: {dict_time:.6f}s")276print(f"Speedup: {list_time/dict_time:.0f}x")277```278279### Pattern 9: Local Variable Access280281```python282import timeit283284# Global variable (slow)285GLOBAL_VALUE = 100286287def use_global():288"""Access global variable."""289total = 0290for i in range(10000):291total += GLOBAL_VALUE292return total293294def use_local():295"""Use local variable."""296local_value = 100297total = 0298for i in range(10000):299total += local_value300return total301302# Local is faster303global_time = timeit.timeit(use_global, number=1000)304local_time = timeit.timeit(use_local, number=1000)305306print(f"Global access: {global_time:.4f}s")307print(f"Local access: {local_time:.4f}s")308print(f"Speedup: {global_time/local_time:.2f}x")309```310311### Pattern 10: Function Call Overhead312313```python314import timeit315316def calculate_inline():317"""Inline calculation."""318total = 0319for i in range(10000):320total += i * 2 + 1321return total322323def helper_function(x):324"""Helper function."""325return x * 2 + 1326327def calculate_with_function():328"""Calculation with function calls."""329total = 0330for i in range(10000):331total += helper_function(i)332return total333334# Inline is faster due to no call overhead335inline_time = timeit.timeit(calculate_inline, number=1000)336function_time = timeit.timeit(calculate_with_function, number=1000)337338print(f"Inline: {inline_time:.4f}s")339print(f"Function calls: {function_time:.4f}s")340```341342For advanced optimization techniques including NumPy vectorization, caching, memory management, parallelization, async I/O, database optimization, and benchmarking tools, see [references/advanced-patterns.md](references/advanced-patterns.md)343