Profile and optimize Python code using cProfile

Python performance optimization

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Python performance optimization cover

Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.

---
name: python-performance-optimization
description: Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.
---

# Python Performance Optimization

Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.

## When to Use This Skill

- Identifying performance bottlenecks in Python applications
- Reducing application latency and response times
- Optimizing CPU-intensive operations
- Reducing memory consumption and memory leaks
- Improving database query performance
- Optimizing I/O operations
- Speeding up data processing pipelines

Overview

Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill python-performance-optimization -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-performance-optimization
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/d0ad23e0f232b0210713/python-performance-optimization.zip" -OutFile "$env:TEMP\python-performance-optimization.zip"; Expand-Archive "$env:TEMP\python-performance-optimization.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md3.2 KB
  • references/2 files · 17.5 KB
Read the files here
wshobson/4236bb93 files
SKILL.md
Show the full text101 lines

Python Performance Optimization

Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.

When to Use This Skill

  • Identifying performance bottlenecks in Python applications
  • Reducing application latency and response times
  • Optimizing CPU-intensive operations
  • Reducing memory consumption and memory leaks
  • Improving database query performance
  • Optimizing I/O operations
  • Speeding up data processing pipelines
  • Implementing high-performance algorithms
  • Profiling production applications

Core Concepts

1. Profiling Types
  • CPU Profiling: Identify time-consuming functions
  • Memory Profiling: Track memory allocation and leaks
  • Line Profiling: Profile at line-by-line granularity
  • Call Graph: Visualize function call relationships
2. Performance Metrics
  • Execution Time: How long operations take
  • Memory Usage: Peak and average memory consumption
  • CPU Utilization: Processor usage patterns
  • I/O Wait: Time spent on I/O operations
3. Optimization Strategies
  • Algorithmic: Better algorithms and data structures
  • Implementation: More efficient code patterns
  • Parallelization: Multi-threading/processing
  • Caching: Avoid redundant computation
  • Native Extensions: C/Rust for critical paths

Quick Start

Basic Timing
import time

def measure_time():
    """Simple timing measurement."""
    start = time.time()

    # Your code here
    result = sum(range(1000000))

    elapsed = time.time() - start
    print(f"Execution time: {elapsed:.4f} seconds")
    return result

# Better: use timeit for accurate measurements
import timeit

execution_time = timeit.timeit(
    "sum(range(1000000))",
    number=100
)
print(f"Average time: {execution_time/100:.6f} seconds")

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

  1. Profile before optimizing - Measure to find real bottlenecks
  2. Focus on hot paths - Optimize code that runs most frequently
  3. Use appropriate data structures - Dict for lookups, set for membership
  4. Avoid premature optimization - Clarity first, then optimize
  5. Use built-in functions - They're implemented in C
  6. Cache expensive computations - Use lru_cache
  7. Batch I/O operations - Reduce system calls
  8. Use generators for large datasets
  9. Consider NumPy for numerical operations
  10. Profile production code - Use py-spy for live systems

Common Pitfalls

  • Optimizing without profiling
  • Using global variables unnecessarily
  • Not using appropriate data structures
  • Creating unnecessary copies of data
  • Not using connection pooling for databases
  • Ignoring algorithmic complexity
  • Over-optimizing rare code paths
  • Not considering memory usage
1---
2name: python-performance-optimization
3description: Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.
4---
5 
6# Python Performance Optimization
7 
8Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.
9 
10## When to Use This Skill
11 
12- Identifying performance bottlenecks in Python applications
13- Reducing application latency and response times
14- Optimizing CPU-intensive operations
15- Reducing memory consumption and memory leaks
16- Improving database query performance
17- Optimizing I/O operations
18- Speeding up data processing pipelines
19- Implementing high-performance algorithms
20- Profiling production applications
21 
22## Core Concepts
23 
24### 1. Profiling Types
25 
26- **CPU Profiling**: Identify time-consuming functions
27- **Memory Profiling**: Track memory allocation and leaks
28- **Line Profiling**: Profile at line-by-line granularity
29- **Call Graph**: Visualize function call relationships
30 
31### 2. Performance Metrics
32 
33- **Execution Time**: How long operations take
34- **Memory Usage**: Peak and average memory consumption
35- **CPU Utilization**: Processor usage patterns
36- **I/O Wait**: Time spent on I/O operations
37 
38### 3. Optimization Strategies
39 
40- **Algorithmic**: Better algorithms and data structures
41- **Implementation**: More efficient code patterns
42- **Parallelization**: Multi-threading/processing
43- **Caching**: Avoid redundant computation
44- **Native Extensions**: C/Rust for critical paths
45 
46## Quick Start
47 
48### Basic Timing
49 
50```python
51import time
52 
53def measure_time():
54 """Simple timing measurement."""
55 start = time.time()
56 
57 # Your code here
58 result = sum(range(1000000))
59 
60 elapsed = time.time() - start
61 print(f"Execution time: {elapsed:.4f} seconds")
62 return result
63 
64# Better: use timeit for accurate measurements
65import timeit
66 
67execution_time = timeit.timeit(
68 "sum(range(1000000))",
69 number=100
70)
71print(f"Average time: {execution_time/100:.6f} seconds")
72```
73 
74## Detailed patterns and worked examples
75 
76Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
77 
78## Best Practices
79 
801. **Profile before optimizing** - Measure to find real bottlenecks
812. **Focus on hot paths** - Optimize code that runs most frequently
823. **Use appropriate data structures** - Dict for lookups, set for membership
834. **Avoid premature optimization** - Clarity first, then optimize
845. **Use built-in functions** - They're implemented in C
856. **Cache expensive computations** - Use lru_cache
867. **Batch I/O operations** - Reduce system calls
878. **Use generators** for large datasets
889. **Consider NumPy** for numerical operations
8910. **Profile production code** - Use py-spy for live systems
90 
91## Common Pitfalls
92 
93- Optimizing without profiling
94- Using global variables unnecessarily
95- Not using appropriate data structures
96- Creating unnecessary copies of data
97- Not using connection pooling for databases
98- Ignoring algorithmic complexity
99- Over-optimizing rare code paths
100- Not considering memory usage
101 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillDiagnose why a specific ad creative is winning or losingCreative performance analysisgmmh1/claude-paid-media-skills · by gmmh1Diagnose why a specific ad creative is winning or losing using the generalized hook-hold-click-convert funnel, applicable across any platform. Triggers on 'why is this ad underperforming', 'diagnose my creative', or 'where in the funnel is this ad failing'. Platform-agnostic diagnostic framework — platform-specific versions (meta-ads-creative-analytics) apply this with platform-native metrics.New listingPromptAct as a professional full-stack developer taskedProfessional Full-Stack Developer for Network Mapping & Monitoring Applicationf/prompts.chat · by Yohanes Farly RakinaungAct as a professional full-stack developer tasked with building a web application for mapping and monitoring networks using Mikrotik Netwatch API. Implement multi-user role-based management to handle devices, monitor their status, and manage user subscriptions.New listingSkillEstablishes a project's quality bar as a written contractConstraint driven developmentaddyosmani/agent-skills · by addyosmaniEstablishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.★ 98.7k GitHub starsSkillInstruments code so production behavior is visibleObservability and instrumentationaddyosmani/agent-skills · by addyosmaniInstruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.★ 98.7k GitHub starsSkillOptimizes application performance across frontend, backendPerformance optimizationaddyosmani/agent-skills · by addyosmaniOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.★ 98.7k GitHub starsSkillDiscovers and invokes agent skillsUsing agent skillsaddyosmani/agent-skills · by addyosmaniDiscovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked.★ 98.7k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars