Introduction
Techniques for optimizing Python application performance.
Profiling
import cProfile
import pstats
# Profile function
cProfile.run("my_function()", "stats.prof")
# Analyze results
pstats.Stats("stats.prof").sort_stats("cumulative").print_stats(10)
Line Profiler
# pip install line_profiler
# Add @profile decorator
from line_profiler import LineProfiler
profiler = LineProfiler()
profiler.add_function(my_function)
profiler.runcall(my_function, args)
profiler.print_stats()
Optimization Tips
# Local variable access is faster
def fast_function():
local_var = expensive_operation
for item in items:
result = local_var + item # Faster than global
return result
# Use list comprehensions instead of loops
result = [x ** 2 for x in range(1000)]
# Use join instead of concatenation
parts = ["a", "b", "c"]
result = "".join(parts)
Practice Problems
- Profile code to find bottlenecks
- Optimize hot paths
- Use appropriate data structures
- Reduce function call overhead
- Use compiled extensions