[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EAVB2SKATSX4K5X2SQV86A":3,"skill-same:01M6EAVB2SKATSX4K5X2SQV86A":172},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":42,"ownerHtmlUrl":43,"ownerBlogUrl":6,"ownerDescription":44,"updatedAt":45,"install":46,"resources":59},"01M6EAVB2SKATSX4K5X2SQV86A","python-performance-optimization",null,"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.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FHarmeet10000\u002Fskills\u002Fpython-performance-optimization\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31],"python","performance","Optimization","performance optimization","python performance optimization","memory","debugging","code","best practices","profile","use","optimize","application","2026-11-10 10:12:30",false,"---\nname: python-performance-optimization\ndescription: 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.\n---\n\n# Python Performance Optimization\n\nComprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.\n\n## When to Use This Skill\n\n- Identifying performance bottlenecks in Python applications\n- Reducing application latency and response times\n- Optimizing CPU-intensive operations\n- Reducing memory consumption and memory leaks\n- Improving database query performance\n- Optimizing I\u002FO operations\n- Speeding up data processing pipelines\n- Implementing high-performance algorithms\n- Profiling production applications\n\n## Core Concepts\n\n### 1. Profiling Types\n\n- **CPU Profiling**: Identify time-consuming functions\n- **Memory Profiling**: Track memory allocation and leaks\n- **Line Profiling**: Profile at line-by-line granularity\n- **Call Graph**: Visualize function call relationships\n\n### 2. Performance Metrics\n\n- **Execution Time**: How long operations take\n- **Memory Usage**: Peak and average memory consumption\n- **CPU Utilization**: Processor usage patterns\n- **I\u002FO Wait**: Time spent on I\u002FO operations\n\n### 3. Optimization Strategies\n\n- **Algorithmic**: Better algorithms and data structures\n- **Implementation**: More efficient code patterns\n- **Parallelization**: Multi-threading\u002Fprocessing\n- **Caching**: Avoid redundant computation\n- **Native Extensions**: C\u002FRust for critical paths\n\n## Quick Start\n\n### Basic Timing\n\n```python\nimport time\n\ndef measure_time():\n    \"\"\"Simple timing measurement.\"\"\"\n    start = time.time()\n\n    # Your code here\n    result = sum(range(1000000))\n\n    elapsed = time.time() - start\n    print(f\"Execution time: {elapsed:.4f} seconds\")\n    return result\n\n# Better: use timeit for accurate measurements\nimport timeit\n\nexecution_time = timeit.timeit(\n    \"sum(range(1000000))\",\n    number=100\n)\nprint(f\"Average time: {execution_time\u002F100:.6f} seconds\")\n```\n\n## Profiling Tools\n\n### Pattern 1: cProfile - CPU Profiling\n\n```python\nimport cProfile\nimport pstats\nfrom pstats import SortKey\n\ndef slow_function():\n    \"\"\"Function to profile.\"\"\"\n    total = 0\n    for i in range(1000000):\n        total += i\n    return total\n\ndef another_function():\n    \"\"\"Another function.\"\"\"\n    return [i**2 for i in range(100000)]\n\ndef main():\n    \"\"\"Main function to profile.\"\"\"\n    result1 = slow_function()\n    result2 = another_function()\n    return result1, result2\n\n# Profile the code\nif __name__ == \"__main__\":\n    profiler = cProfile.Profile()\n    profiler.enable()\n\n    main()\n\n    profiler.disable()\n\n    # Print stats\n    stats = pstats.Stats(profiler)\n    stats.sort_stats(SortKey.CUMULATIVE)\n    stats.print_stats(10)  # Top 10 functions\n\n    # Save to file for later analysis\n    stats.dump_stats(\"profile_output.prof\")\n```\n\n**Command-line profiling:**\n\n```bash\n# Profile a script\npython -m cProfile -o output.prof script.py\n\n# View results\npython -m pstats output.prof\n# In pstats:\n# sort cumtime\n# stats 10\n```\n\n### Pattern 2: line_profiler - Line-by-Line Profiling\n\n```python\n# Install: pip install line-profiler\n\n# Add @profile decorator (line_profiler provides this)\n@profile\ndef process_data(data):\n    \"\"\"Process data with line profiling.\"\"\"\n    result = []\n    for item in data:\n        processed = item * 2\n        result.append(processed)\n    return result\n\n# Run with:\n# kernprof -l -v script.py\n```\n\n**Manual line profiling:**\n\n```python\nfrom line_profiler import LineProfiler\n\ndef process_data(data):\n    \"\"\"Function to profile.\"\"\"\n    result = []\n    for item in data:\n        processed = item * 2\n        result.append(processed)\n    return result\n\nif __name__ == \"__main__\":\n    lp = LineProfiler()\n    lp.add_function(process_data)\n\n    data = list(range(100000))\n\n    lp_wrapper = lp(process_data)\n    lp_wrapper(data)\n\n    lp.print_stats()\n```\n\n### Pattern 3: memory_profiler - Memory Usage\n\n```python\n# Install: pip install memory-profiler\n\nfrom memory_profiler import profile\n\n@profile\ndef memory_intensive():\n    \"\"\"Function that uses lots of memory.\"\"\"\n    # Create large list\n    big_list = [i for i in range(1000000)]\n\n    # Create large dict\n    big_dict = {i: i**2 for i in range(100000)}\n\n    # Process data\n    result = sum(big_list)\n\n    return result\n\nif __name__ == \"__main__\":\n    memory_intensive()\n\n# Run with:\n# python -m memory_profiler script.py\n```\n\n### Pattern 4: py-spy - Production Profiling\n\n```bash\n# Install: pip install py-spy\n\n# Profile a running Python process\npy-spy top --pid 12345\n\n# Generate flamegraph\npy-spy record -o profile.svg --pid 12345\n\n# Profile a script\npy-spy record -o profile.svg -- python script.py\n\n# Dump current call stack\npy-spy dump --pid 12345\n```\n\n## Optimization Patterns\n\n### Pattern 5: List Comprehensions vs Loops\n\n```python\nimport timeit\n\n# Slow: Traditional loop\ndef slow_squares(n):\n    \"\"\"Create list of squares using loop.\"\"\"\n    result = []\n    for i in range(n):\n        result.append(i**2)\n    return result\n\n# Fast: List comprehension\ndef fast_squares(n):\n    \"\"\"Create list of squares using comprehension.\"\"\"\n    return [i**2 for i in range(n)]\n\n# Benchmark\nn = 100000\n\nslow_time = timeit.timeit(lambda: slow_squares(n), number=100)\nfast_time = timeit.timeit(lambda: fast_squares(n), number=100)\n\nprint(f\"Loop: {slow_time:.4f}s\")\nprint(f\"Comprehension: {fast_time:.4f}s\")\nprint(f\"Speedup: {slow_time\u002Ffast_time:.2f}x\")\n\n# Even faster for simple operations: map\ndef faster_squares(n):\n    \"\"\"Use map for even better performance.\"\"\"\n    return list(map(lambda x: x**2, range(n)))\n```\n\n### Pattern 6: Generator Expressions for Memory\n\n```python\nimport sys\n\ndef list_approach():\n    \"\"\"Memory-intensive list.\"\"\"\n    data = [i**2 for i in range(1000000)]\n    return sum(data)\n\ndef generator_approach():\n    \"\"\"Memory-efficient generator.\"\"\"\n    data = (i**2 for i in range(1000000))\n    return sum(data)\n\n# Memory comparison\nlist_data = [i for i in range(1000000)]\ngen_data = (i for i in range(1000000))\n\nprint(f\"List size: {sys.getsizeof(list_data)} bytes\")\nprint(f\"Generator size: {sys.getsizeof(gen_data)} bytes\")\n\n# Generators use constant memory regardless of size\n```\n\n### Pattern 7: String Concatenation\n\n```python\nimport timeit\n\ndef slow_concat(items):\n    \"\"\"Slow string concatenation.\"\"\"\n    result = \"\"\n    for item in items:\n        result += str(item)\n    return result\n\ndef fast_concat(items):\n    \"\"\"Fast string concatenation with join.\"\"\"\n    return \"\".join(str(item) for item in items)\n\ndef faster_concat(items):\n    \"\"\"Even faster with list.\"\"\"\n    parts = [str(item) for item in items]\n    return \"\".join(parts)\n\nitems = list(range(10000))\n\n# Benchmark\nslow = timeit.timeit(lambda: slow_concat(items), number=100)\nfast = timeit.timeit(lambda: fast_concat(items), number=100)\nfaster = timeit.timeit(lambda: faster_concat(items), number=100)\n\nprint(f\"Concatenation (+): {slow:.4f}s\")\nprint(f\"Join (generator): {fast:.4f}s\")\nprint(f\"Join (list): {faster:.4f}s\")\n```\n\n### Pattern 8: Dictionary Lookups vs List Searches\n\n```python\nimport timeit\n\n# Create test data\nsize = 10000\nitems = list(range(size))\nlookup_dict = {i: i for i in range(size)}\n\ndef list_search(items, target):\n    \"\"\"O(n) search in list.\"\"\"\n    return target in items\n\ndef dict_search(lookup_dict, target):\n    \"\"\"O(1) search in dict.\"\"\"\n    return target in lookup_dict\n\ntarget = size - 1  # Worst case for list\n\n# Benchmark\nlist_time = timeit.timeit(\n    lambda: list_search(items, target),\n    number=1000\n)\ndict_time = timeit.timeit(\n    lambda: dict_search(lookup_dict, target),\n    number=1000\n)\n\nprint(f\"List search: {list_time:.6f}s\")\nprint(f\"Dict search: {dict_time:.6f}s\")\nprint(f\"Speedup: {list_time\u002Fdict_time:.0f}x\")\n```\n\n### Pattern 9: Local Variable Access\n\n```python\nimport timeit\n\n# Global variable (slow)\nGLOBAL_VALUE = 100\n\ndef use_global():\n    \"\"\"Access global variable.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += GLOBAL_VALUE\n    return total\n\ndef use_local():\n    \"\"\"Use local variable.\"\"\"\n    local_value = 100\n    total = 0\n    for i in range(10000):\n        total += local_value\n    return total\n\n# Local is faster\nglobal_time = timeit.timeit(use_global, number=1000)\nlocal_time = timeit.timeit(use_local, number=1000)\n\nprint(f\"Global access: {global_time:.4f}s\")\nprint(f\"Local access: {local_time:.4f}s\")\nprint(f\"Speedup: {global_time\u002Flocal_time:.2f}x\")\n```\n\n### Pattern 10: Function Call Overhead\n\n```python\nimport timeit\n\ndef calculate_inline():\n    \"\"\"Inline calculation.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += i * 2 + 1\n    return total\n\ndef helper_function(x):\n    \"\"\"Helper function.\"\"\"\n    return x * 2 + 1\n\ndef calculate_with_function():\n    \"\"\"Calculation with function calls.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += helper_function(i)\n    return total\n\n# Inline is faster due to no call overhead\ninline_time = timeit.timeit(calculate_inline, number=1000)\nfunction_time = timeit.timeit(calculate_with_function, number=1000)\n\nprint(f\"Inline: {inline_time:.4f}s\")\nprint(f\"Function calls: {function_time:.4f}s\")\n```\n\n## Advanced Optimization\n\n### Pattern 11: NumPy for Numerical Operations\n\n```python\nimport timeit\nimport numpy as np\n\ndef python_sum(n):\n    \"\"\"Sum using pure Python.\"\"\"\n    return sum(range(n))\n\ndef numpy_sum(n):\n    \"\"\"Sum using NumPy.\"\"\"\n    return np.arange(n).sum()\n\nn = 1000000\n\npython_time = timeit.timeit(lambda: python_sum(n), number=100)\nnumpy_time = timeit.timeit(lambda: numpy_sum(n), number=100)\n\nprint(f\"Python: {python_time:.4f}s\")\nprint(f\"NumPy: {numpy_time:.4f}s\")\nprint(f\"Speedup: {python_time\u002Fnumpy_time:.2f}x\")\n\n# Vectorized operations\ndef python_multiply():\n    \"\"\"Element-wise multiplication in Python.\"\"\"\n    a = list(range(100000))\n    b = list(range(100000))\n    return [x * y for x, y in zip(a, b)]\n\ndef numpy_multiply():\n    \"\"\"Vectorized multiplication in NumPy.\"\"\"\n    a = np.arange(100000)\n    b = np.arange(100000)\n    return a * b\n\npy_time = timeit.timeit(python_multiply, number=100)\nnp_time = timeit.timeit(numpy_multiply, number=100)\n\nprint(f\"\\nPython multiply: {py_time:.4f}s\")\nprint(f\"NumPy multiply: {np_time:.4f}s\")\nprint(f\"Speedup: {py_time\u002Fnp_time:.2f}x\")\n```\n\n### Pattern 12: Caching with functools.lru_cache\n\n```python\nfrom functools import lru_cache\nimport timeit\n\ndef fibonacci_slow(n):\n    \"\"\"Recursive fibonacci without caching.\"\"\"\n    if n \u003C 2:\n        return n\n    return fibonacci_slow(n-1) + fibonacci_slow(n-2)\n\n@lru_cache(maxsize=None)\ndef fibonacci_fast(n):\n    \"\"\"Recursive fibonacci with caching.\"\"\"\n    if n \u003C 2:\n        return n\n    return fibonacci_fast(n-1) + fibonacci_fast(n-2)\n\n# Massive speedup for recursive algorithms\nn = 30\n\nslow_time = timeit.timeit(lambda: fibonacci_slow(n), number=1)\nfast_time = timeit.timeit(lambda: fibonacci_fast(n), number=1000)\n\nprint(f\"Without cache (1 run): {slow_time:.4f}s\")\nprint(f\"With cache (1000 runs): {fast_time:.4f}s\")\n\n# Cache info\nprint(f\"Cache info: {fibonacci_fast.cache_info()}\")\n```\n\n### Pattern 13: Using **slots** for Memory\n\n```python\nimport sys\n\nclass RegularClass:\n    \"\"\"Regular class with __dict__.\"\"\"\n    def __init__(self, x, y, z):\n        self.x = x\n        self.y = y\n        self.z = z\n\nclass SlottedClass:\n    \"\"\"Class with __slots__ for memory efficiency.\"\"\"\n    __slots__ = ['x', 'y', 'z']\n\n    def __init__(self, x, y, z):\n        self.x = x\n        self.y = y\n        self.z = z\n\n# Memory comparison\nregular = RegularClass(1, 2, 3)\nslotted = SlottedClass(1, 2, 3)\n\nprint(f\"Regular class size: {sys.getsizeof(regular)} bytes\")\nprint(f\"Slotted class size: {sys.getsizeof(slotted)} bytes\")\n\n# Significant savings with many instances\nregular_objects = [RegularClass(i, i+1, i+2) for i in range(10000)]\nslotted_objects = [SlottedClass(i, i+1, i+2) for i in range(10000)]\n\nprint(f\"\\nMemory for 10000 regular objects: ~{sys.getsizeof(regular) * 10000} bytes\")\nprint(f\"Memory for 10000 slotted objects: ~{sys.getsizeof(slotted) * 10000} bytes\")\n```\n\n### Pattern 14: Multiprocessing for CPU-Bound Tasks\n\n```python\nimport multiprocessing as mp\nimport time\n\ndef cpu_intensive_task(n):\n    \"\"\"CPU-intensive calculation.\"\"\"\n    return sum(i**2 for i in range(n))\n\ndef sequential_processing():\n    \"\"\"Process tasks sequentially.\"\"\"\n    start = time.time()\n    results = [cpu_intensive_task(1000000) for _ in range(4)]\n    elapsed = time.time() - start\n    return elapsed, results\n\ndef parallel_processing():\n    \"\"\"Process tasks in parallel.\"\"\"\n    start = time.time()\n    with mp.Pool(processes=4) as pool:\n        results = pool.map(cpu_intensive_task, [1000000] * 4)\n    elapsed = time.time() - start\n    return elapsed, results\n\nif __name__ == \"__main__\":\n    seq_time, seq_results = sequential_processing()\n    par_time, par_results = parallel_processing()\n\n    print(f\"Sequential: {seq_time:.2f}s\")\n    print(f\"Parallel: {par_time:.2f}s\")\n    print(f\"Speedup: {seq_time\u002Fpar_time:.2f}x\")\n```\n\n### Pattern 15: Async I\u002FO for I\u002FO-Bound Tasks\n\n```python\nimport asyncio\nimport aiohttp\nimport time\nimport requests\n\nurls = [\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n]\n\ndef synchronous_requests():\n    \"\"\"Synchronous HTTP requests.\"\"\"\n    start = time.time()\n    results = []\n    for url in urls:\n        response = requests.get(url)\n        results.append(response.status_code)\n    elapsed = time.time() - start\n    return elapsed, results\n\nasync def async_fetch(session, url):\n    \"\"\"Async HTTP request.\"\"\"\n    async with session.get(url) as response:\n        return response.status\n\nasync def asynchronous_requests():\n    \"\"\"Asynchronous HTTP requests.\"\"\"\n    start = time.time()\n    async with aiohttp.ClientSession() as session:\n        tasks = [async_fetch(session, url) for url in urls]\n        results = await asyncio.gather(*tasks)\n    elapsed = time.time() - start\n    return elapsed, results\n\n# Async is much faster for I\u002FO-bound work\nsync_time, sync_results = synchronous_requests()\nasync_time, async_results = asyncio.run(asynchronous_requests())\n\nprint(f\"Synchronous: {sync_time:.2f}s\")\nprint(f\"Asynchronous: {async_time:.2f}s\")\nprint(f\"Speedup: {sync_time\u002Fasync_time:.2f}x\")\n```\n\n## Database Optimization\n\n### Pattern 16: Batch Database Operations\n\n```python\nimport sqlite3\nimport time\n\ndef create_db():\n    \"\"\"Create test database.\"\"\"\n    conn = sqlite3.connect(\":memory:\")\n    conn.execute(\"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)\")\n    return conn\n\ndef slow_inserts(conn, count):\n    \"\"\"Insert records one at a time.\"\"\"\n    start = time.time()\n    cursor = conn.cursor()\n    for i in range(count):\n        cursor.execute(\"INSERT INTO users (name) VALUES (?)\", (f\"User {i}\",))\n        conn.commit()  # Commit each insert\n    elapsed = time.time() - start\n    return elapsed\n\ndef fast_inserts(conn, count):\n    \"\"\"Batch insert with single commit.\"\"\"\n    start = time.time()\n    cursor = conn.cursor()\n    data = [(f\"User {i}\",) for i in range(count)]\n    cursor.executemany(\"INSERT INTO users (name) VALUES (?)\", data)\n    conn.commit()  # Single commit\n    elapsed = time.time() - start\n    return elapsed\n\n# Benchmark\nconn1 = create_db()\nslow_time = slow_inserts(conn1, 1000)\n\nconn2 = create_db()\nfast_time = fast_inserts(conn2, 1000)\n\nprint(f\"Individual inserts: {slow_time:.4f}s\")\nprint(f\"Batch insert: {fast_time:.4f}s\")\nprint(f\"Speedup: {slow_time\u002Ffast_time:.2f}x\")\n```\n\n### Pattern 17: Query Optimization\n\n```python\n# Use indexes for frequently queried columns\n\"\"\"\n-- Slow: No index\nSELECT * FROM users WHERE email = 'user@example.com';\n\n-- Fast: With index\nCREATE INDEX idx_users_email ON users(email);\nSELECT * FROM users WHERE email = 'user@example.com';\n\"\"\"\n\n# Use query planning\nimport sqlite3\n\nconn = sqlite3.connect(\"example.db\")\ncursor = conn.cursor()\n\n# Analyze query performance\ncursor.execute(\"EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = ?\", (\"test@example.com\",))\nprint(cursor.fetchall())\n\n# Use SELECT only needed columns\n# Slow: SELECT *\n# Fast: SELECT id, name\n```\n\n## Memory Optimization\n\n### Pattern 18: Detecting Memory Leaks\n\n```python\nimport tracemalloc\nimport gc\n\ndef memory_leak_example():\n    \"\"\"Example that leaks memory.\"\"\"\n    leaked_objects = []\n\n    for i in range(100000):\n        # Objects added but never removed\n        leaked_objects.append([i] * 100)\n\n    # In real code, this would be an unintended reference\n\ndef track_memory_usage():\n    \"\"\"Track memory allocations.\"\"\"\n    tracemalloc.start()\n\n    # Take snapshot before\n    snapshot1 = tracemalloc.take_snapshot()\n\n    # Run code\n    memory_leak_example()\n\n    # Take snapshot after\n    snapshot2 = tracemalloc.take_snapshot()\n\n    # Compare\n    top_stats = snapshot2.compare_to(snapshot1, 'lineno')\n\n    print(\"Top 10 memory allocations:\")\n    for stat in top_stats[:10]:\n        print(stat)\n\n    tracemalloc.stop()\n\n# Monitor memory\ntrack_memory_usage()\n\n# Force garbage collection\ngc.collect()\n```\n\n### Pattern 19: Iterators vs Lists\n\n```python\nimport sys\n\ndef process_file_list(filename):\n    \"\"\"Load entire file into memory.\"\"\"\n    with open(filename) as f:\n        lines = f.readlines()  # Loads all lines\n        return sum(1 for line in lines if line.strip())\n\ndef process_file_iterator(filename):\n    \"\"\"Process file line by line.\"\"\"\n    with open(filename) as f:\n        return sum(1 for line in f if line.strip())\n\n# Iterator uses constant memory\n# List loads entire file into memory\n```\n\n### Pattern 20: Weakref for Caches\n\n```python\nimport weakref\n\nclass CachedResource:\n    \"\"\"Resource that can be garbage collected.\"\"\"\n    def __init__(self, data):\n        self.data = data\n\n# Regular cache prevents garbage collection\nregular_cache = {}\n\ndef get_resource_regular(key):\n    \"\"\"Get resource from regular cache.\"\"\"\n    if key not in regular_cache:\n        regular_cache[key] = CachedResource(f\"Data for {key}\")\n    return regular_cache[key]\n\n# Weak reference cache allows garbage collection\nweak_cache = weakref.WeakValueDictionary()\n\ndef get_resource_weak(key):\n    \"\"\"Get resource from weak cache.\"\"\"\n    resource = weak_cache.get(key)\n    if resource is None:\n        resource = CachedResource(f\"Data for {key}\")\n        weak_cache[key] = resource\n    return resource\n\n# When no strong references exist, objects can be GC'd\n```\n\n## Benchmarking Tools\n\n### Custom Benchmark Decorator\n\n```python\nimport time\nfrom functools import wraps\n\ndef benchmark(func):\n    \"\"\"Decorator to benchmark function execution.\"\"\"\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.6f} seconds\")\n        return result\n    return wrapper\n\n@benchmark\ndef slow_function():\n    \"\"\"Function to benchmark.\"\"\"\n    time.sleep(0.5)\n    return sum(range(1000000))\n\nresult = slow_function()\n```\n\n### Performance Testing with pytest-benchmark\n\n```python\n# Install: pip install pytest-benchmark\n\ndef test_list_comprehension(benchmark):\n    \"\"\"Benchmark list comprehension.\"\"\"\n    result = benchmark(lambda: [i**2 for i in range(10000)])\n    assert len(result) == 10000\n\ndef test_map_function(benchmark):\n    \"\"\"Benchmark map function.\"\"\"\n    result = benchmark(lambda: list(map(lambda x: x**2, range(10000))))\n    assert len(result) == 10000\n\n# Run with: pytest test_performance.py --benchmark-compare\n```\n\n## Best Practices\n\n1. **Profile before optimizing** - Measure to find real bottlenecks\n2. **Focus on hot paths** - Optimize code that runs most frequently\n3. **Use appropriate data structures** - Dict for lookups, set for membership\n4. **Avoid premature optimization** - Clarity first, then optimize\n5. **Use built-in functions** - They're implemented in C\n6. **Cache expensive computations** - Use lru_cache\n7. **Batch I\u002FO operations** - Reduce system calls\n8. **Use generators** for large datasets\n9. **Consider NumPy** for numerical operations\n10. **Profile production code** - Use py-spy for live systems\n\n## Common Pitfalls\n\n- Optimizing without profiling\n- Using global variables unnecessarily\n- Not using appropriate data structures\n- Creating unnecessary copies of data\n- Not using connection pooling for databases\n- Ignoring algorithmic complexity\n- Over-optimizing rare code paths\n- Not considering memory usage\n\n## Resources\n\n- **cProfile**: Built-in CPU profiler\n- **memory_profiler**: Memory usage profiling\n- **line_profiler**: Line-by-line profiling\n- **py-spy**: Sampling profiler for production\n- **NumPy**: High-performance numerical computing\n- **Cython**: Compile Python to C\n- **PyPy**: Alternative Python interpreter with JIT\n\n## Performance Checklist\n\n- [ ] Profiled code to identify bottlenecks\n- [ ] Used appropriate data structures\n- [ ] Implemented caching where beneficial\n- [ ] Optimized database queries\n- [ ] Used generators for large datasets\n- [ ] Considered multiprocessing for CPU-bound tasks\n- [ ] Used async I\u002FO for I\u002FO-bound tasks\n- [ ] Minimized function call overhead in hot loops\n- [ ] Checked for memory leaks\n- [ ] Benchmarked before and after optimization\n","# Python Performance Optimization\n\nComprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.\n\n## When to Use This Skill\n\n- Identifying performance bottlenecks in Python applications\n- Reducing application latency and response times\n- Optimizing CPU-intensive operations\n- Reducing memory consumption and memory leaks\n- Improving database query performance\n- Optimizing I\u002FO operations\n- Speeding up data processing pipelines\n- Implementing high-performance algorithms\n- Profiling production applications\n\n## Core Concepts\n\n### 1. Profiling Types\n\n- **CPU Profiling**: Identify time-consuming functions\n- **Memory Profiling**: Track memory allocation and leaks\n- **Line Profiling**: Profile at line-by-line granularity\n- **Call Graph**: Visualize function call relationships\n\n### 2. Performance Metrics\n\n- **Execution Time**: How long operations take\n- **Memory Usage**: Peak and average memory consumption\n- **CPU Utilization**: Processor usage patterns\n- **I\u002FO Wait**: Time spent on I\u002FO operations\n\n### 3. Optimization Strategies\n\n- **Algorithmic**: Better algorithms and data structures\n- **Implementation**: More efficient code patterns\n- **Parallelization**: Multi-threading\u002Fprocessing\n- **Caching**: Avoid redundant computation\n- **Native Extensions**: C\u002FRust for critical paths\n\n## Quick Start\n\n### Basic Timing\n\n```python\nimport time\n\ndef measure_time():\n    \"\"\"Simple timing measurement.\"\"\"\n    start = time.time()\n\n    # Your code here\n    result = sum(range(1000000))\n\n    elapsed = time.time() - start\n    print(f\"Execution time: {elapsed:.4f} seconds\")\n    return result\n\n# Better: use timeit for accurate measurements\nimport timeit\n\nexecution_time = timeit.timeit(\n    \"sum(range(1000000))\",\n    number=100\n)\nprint(f\"Average time: {execution_time\u002F100:.6f} seconds\")\n```\n\n## Profiling Tools\n\n### Pattern 1: cProfile - CPU Profiling\n\n```python\nimport cProfile\nimport pstats\nfrom pstats import SortKey\n\ndef slow_function():\n    \"\"\"Function to profile.\"\"\"\n    total = 0\n    for i in range(1000000):\n        total += i\n    return total\n\ndef another_function():\n    \"\"\"Another function.\"\"\"\n    return [i**2 for i in range(100000)]\n\ndef main():\n    \"\"\"Main function to profile.\"\"\"\n    result1 = slow_function()\n    result2 = another_function()\n    return result1, result2\n\n# Profile the code\nif __name__ == \"__main__\":\n    profiler = cProfile.Profile()\n    profiler.enable()\n\n    main()\n\n    profiler.disable()\n\n    # Print stats\n    stats = pstats.Stats(profiler)\n    stats.sort_stats(SortKey.CUMULATIVE)\n    stats.print_stats(10)  # Top 10 functions\n\n    # Save to file for later analysis\n    stats.dump_stats(\"profile_output.prof\")\n```\n\n**Command-line profiling:**\n\n```bash\n# Profile a script\npython -m cProfile -o output.prof script.py\n\n# View results\npython -m pstats output.prof\n# In pstats:\n# sort cumtime\n# stats 10\n```\n\n### Pattern 2: line_profiler - Line-by-Line Profiling\n\n```python\n# Install: pip install line-profiler\n\n# Add @profile decorator (line_profiler provides this)\n@profile\ndef process_data(data):\n    \"\"\"Process data with line profiling.\"\"\"\n    result = []\n    for item in data:\n        processed = item * 2\n        result.append(processed)\n    return result\n\n# Run with:\n# kernprof -l -v script.py\n```\n\n**Manual line profiling:**\n\n```python\nfrom line_profiler import LineProfiler\n\ndef process_data(data):\n    \"\"\"Function to profile.\"\"\"\n    result = []\n    for item in data:\n        processed = item * 2\n        result.append(processed)\n    return result\n\nif __name__ == \"__main__\":\n    lp = LineProfiler()\n    lp.add_function(process_data)\n\n    data = list(range(100000))\n\n    lp_wrapper = lp(process_data)\n    lp_wrapper(data)\n\n    lp.print_stats()\n```\n\n### Pattern 3: memory_profiler - Memory Usage\n\n```python\n# Install: pip install memory-profiler\n\nfrom memory_profiler import profile\n\n@profile\ndef memory_intensive():\n    \"\"\"Function that uses lots of memory.\"\"\"\n    # Create large list\n    big_list = [i for i in range(1000000)]\n\n    # Create large dict\n    big_dict = {i: i**2 for i in range(100000)}\n\n    # Process data\n    result = sum(big_list)\n\n    return result\n\nif __name__ == \"__main__\":\n    memory_intensive()\n\n# Run with:\n# python -m memory_profiler script.py\n```\n\n### Pattern 4: py-spy - Production Profiling\n\n```bash\n# Install: pip install py-spy\n\n# Profile a running Python process\npy-spy top --pid 12345\n\n# Generate flamegraph\npy-spy record -o profile.svg --pid 12345\n\n# Profile a script\npy-spy record -o profile.svg -- python script.py\n\n# Dump current call stack\npy-spy dump --pid 12345\n```\n\n## Optimization Patterns\n\n### Pattern 5: List Comprehensions vs Loops\n\n```python\nimport timeit\n\n# Slow: Traditional loop\ndef slow_squares(n):\n    \"\"\"Create list of squares using loop.\"\"\"\n    result = []\n    for i in range(n):\n        result.append(i**2)\n    return result\n\n# Fast: List comprehension\ndef fast_squares(n):\n    \"\"\"Create list of squares using comprehension.\"\"\"\n    return [i**2 for i in range(n)]\n\n# Benchmark\nn = 100000\n\nslow_time = timeit.timeit(lambda: slow_squares(n), number=100)\nfast_time = timeit.timeit(lambda: fast_squares(n), number=100)\n\nprint(f\"Loop: {slow_time:.4f}s\")\nprint(f\"Comprehension: {fast_time:.4f}s\")\nprint(f\"Speedup: {slow_time\u002Ffast_time:.2f}x\")\n\n# Even faster for simple operations: map\ndef faster_squares(n):\n    \"\"\"Use map for even better performance.\"\"\"\n    return list(map(lambda x: x**2, range(n)))\n```\n\n### Pattern 6: Generator Expressions for Memory\n\n```python\nimport sys\n\ndef list_approach():\n    \"\"\"Memory-intensive list.\"\"\"\n    data = [i**2 for i in range(1000000)]\n    return sum(data)\n\ndef generator_approach():\n    \"\"\"Memory-efficient generator.\"\"\"\n    data = (i**2 for i in range(1000000))\n    return sum(data)\n\n# Memory comparison\nlist_data = [i for i in range(1000000)]\ngen_data = (i for i in range(1000000))\n\nprint(f\"List size: {sys.getsizeof(list_data)} bytes\")\nprint(f\"Generator size: {sys.getsizeof(gen_data)} bytes\")\n\n# Generators use constant memory regardless of size\n```\n\n### Pattern 7: String Concatenation\n\n```python\nimport timeit\n\ndef slow_concat(items):\n    \"\"\"Slow string concatenation.\"\"\"\n    result = \"\"\n    for item in items:\n        result += str(item)\n    return result\n\ndef fast_concat(items):\n    \"\"\"Fast string concatenation with join.\"\"\"\n    return \"\".join(str(item) for item in items)\n\ndef faster_concat(items):\n    \"\"\"Even faster with list.\"\"\"\n    parts = [str(item) for item in items]\n    return \"\".join(parts)\n\nitems = list(range(10000))\n\n# Benchmark\nslow = timeit.timeit(lambda: slow_concat(items), number=100)\nfast = timeit.timeit(lambda: fast_concat(items), number=100)\nfaster = timeit.timeit(lambda: faster_concat(items), number=100)\n\nprint(f\"Concatenation (+): {slow:.4f}s\")\nprint(f\"Join (generator): {fast:.4f}s\")\nprint(f\"Join (list): {faster:.4f}s\")\n```\n\n### Pattern 8: Dictionary Lookups vs List Searches\n\n```python\nimport timeit\n\n# Create test data\nsize = 10000\nitems = list(range(size))\nlookup_dict = {i: i for i in range(size)}\n\ndef list_search(items, target):\n    \"\"\"O(n) search in list.\"\"\"\n    return target in items\n\ndef dict_search(lookup_dict, target):\n    \"\"\"O(1) search in dict.\"\"\"\n    return target in lookup_dict\n\ntarget = size - 1  # Worst case for list\n\n# Benchmark\nlist_time = timeit.timeit(\n    lambda: list_search(items, target),\n    number=1000\n)\ndict_time = timeit.timeit(\n    lambda: dict_search(lookup_dict, target),\n    number=1000\n)\n\nprint(f\"List search: {list_time:.6f}s\")\nprint(f\"Dict search: {dict_time:.6f}s\")\nprint(f\"Speedup: {list_time\u002Fdict_time:.0f}x\")\n```\n\n### Pattern 9: Local Variable Access\n\n```python\nimport timeit\n\n# Global variable (slow)\nGLOBAL_VALUE = 100\n\ndef use_global():\n    \"\"\"Access global variable.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += GLOBAL_VALUE\n    return total\n\ndef use_local():\n    \"\"\"Use local variable.\"\"\"\n    local_value = 100\n    total = 0\n    for i in range(10000):\n        total += local_value\n    return total\n\n# Local is faster\nglobal_time = timeit.timeit(use_global, number=1000)\nlocal_time = timeit.timeit(use_local, number=1000)\n\nprint(f\"Global access: {global_time:.4f}s\")\nprint(f\"Local access: {local_time:.4f}s\")\nprint(f\"Speedup: {global_time\u002Flocal_time:.2f}x\")\n```\n\n### Pattern 10: Function Call Overhead\n\n```python\nimport timeit\n\ndef calculate_inline():\n    \"\"\"Inline calculation.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += i * 2 + 1\n    return total\n\ndef helper_function(x):\n    \"\"\"Helper function.\"\"\"\n    return x * 2 + 1\n\ndef calculate_with_function():\n    \"\"\"Calculation with function calls.\"\"\"\n    total = 0\n    for i in range(10000):\n        total += helper_function(i)\n    return total\n\n# Inline is faster due to no call overhead\ninline_time = timeit.timeit(calculate_inline, number=1000)\nfunction_time = timeit.timeit(calculate_with_function, number=1000)\n\nprint(f\"Inline: {inline_time:.4f}s\")\nprint(f\"Function calls: {function_time:.4f}s\")\n```\n\n## Advanced Optimization\n\n### Pattern 11: NumPy for Numerical Operations\n\n```python\nimport timeit\nimport numpy as np\n\ndef python_sum(n):\n    \"\"\"Sum using pure Python.\"\"\"\n    return sum(range(n))\n\ndef numpy_sum(n):\n    \"\"\"Sum using NumPy.\"\"\"\n    return np.arange(n).sum()\n\nn = 1000000\n\npython_time = timeit.timeit(lambda: python_sum(n), number=100)\nnumpy_time = timeit.timeit(lambda: numpy_sum(n), number=100)\n\nprint(f\"Python: {python_time:.4f}s\")\nprint(f\"NumPy: {numpy_time:.4f}s\")\nprint(f\"Speedup: {python_time\u002Fnumpy_time:.2f}x\")\n\n# Vectorized operations\ndef python_multiply():\n    \"\"\"Element-wise multiplication in Python.\"\"\"\n    a = list(range(100000))\n    b = list(range(100000))\n    return [x * y for x, y in zip(a, b)]\n\ndef numpy_multiply():\n    \"\"\"Vectorized multiplication in NumPy.\"\"\"\n    a = np.arange(100000)\n    b = np.arange(100000)\n    return a * b\n\npy_time = timeit.timeit(python_multiply, number=100)\nnp_time = timeit.timeit(numpy_multiply, number=100)\n\nprint(f\"\\nPython multiply: {py_time:.4f}s\")\nprint(f\"NumPy multiply: {np_time:.4f}s\")\nprint(f\"Speedup: {py_time\u002Fnp_time:.2f}x\")\n```\n\n### Pattern 12: Caching with functools.lru_cache\n\n```python\nfrom functools import lru_cache\nimport timeit\n\ndef fibonacci_slow(n):\n    \"\"\"Recursive fibonacci without caching.\"\"\"\n    if n \u003C 2:\n        return n\n    return fibonacci_slow(n-1) + fibonacci_slow(n-2)\n\n@lru_cache(maxsize=None)\ndef fibonacci_fast(n):\n    \"\"\"Recursive fibonacci with caching.\"\"\"\n    if n \u003C 2:\n        return n\n    return fibonacci_fast(n-1) + fibonacci_fast(n-2)\n\n# Massive speedup for recursive algorithms\nn = 30\n\nslow_time = timeit.timeit(lambda: fibonacci_slow(n), number=1)\nfast_time = timeit.timeit(lambda: fibonacci_fast(n), number=1000)\n\nprint(f\"Without cache (1 run): {slow_time:.4f}s\")\nprint(f\"With cache (1000 runs): {fast_time:.4f}s\")\n\n# Cache info\nprint(f\"Cache info: {fibonacci_fast.cache_info()}\")\n```\n\n### Pattern 13: Using **slots** for Memory\n\n```python\nimport sys\n\nclass RegularClass:\n    \"\"\"Regular class with __dict__.\"\"\"\n    def __init__(self, x, y, z):\n        self.x = x\n        self.y = y\n        self.z = z\n\nclass SlottedClass:\n    \"\"\"Class with __slots__ for memory efficiency.\"\"\"\n    __slots__ = ['x', 'y', 'z']\n\n    def __init__(self, x, y, z):\n        self.x = x\n        self.y = y\n        self.z = z\n\n# Memory comparison\nregular = RegularClass(1, 2, 3)\nslotted = SlottedClass(1, 2, 3)\n\nprint(f\"Regular class size: {sys.getsizeof(regular)} bytes\")\nprint(f\"Slotted class size: {sys.getsizeof(slotted)} bytes\")\n\n# Significant savings with many instances\nregular_objects = [RegularClass(i, i+1, i+2) for i in range(10000)]\nslotted_objects = [SlottedClass(i, i+1, i+2) for i in range(10000)]\n\nprint(f\"\\nMemory for 10000 regular objects: ~{sys.getsizeof(regular) * 10000} bytes\")\nprint(f\"Memory for 10000 slotted objects: ~{sys.getsizeof(slotted) * 10000} bytes\")\n```\n\n### Pattern 14: Multiprocessing for CPU-Bound Tasks\n\n```python\nimport multiprocessing as mp\nimport time\n\ndef cpu_intensive_task(n):\n    \"\"\"CPU-intensive calculation.\"\"\"\n    return sum(i**2 for i in range(n))\n\ndef sequential_processing():\n    \"\"\"Process tasks sequentially.\"\"\"\n    start = time.time()\n    results = [cpu_intensive_task(1000000) for _ in range(4)]\n    elapsed = time.time() - start\n    return elapsed, results\n\ndef parallel_processing():\n    \"\"\"Process tasks in parallel.\"\"\"\n    start = time.time()\n    with mp.Pool(processes=4) as pool:\n        results = pool.map(cpu_intensive_task, [1000000] * 4)\n    elapsed = time.time() - start\n    return elapsed, results\n\nif __name__ == \"__main__\":\n    seq_time, seq_results = sequential_processing()\n    par_time, par_results = parallel_processing()\n\n    print(f\"Sequential: {seq_time:.2f}s\")\n    print(f\"Parallel: {par_time:.2f}s\")\n    print(f\"Speedup: {seq_time\u002Fpar_time:.2f}x\")\n```\n\n### Pattern 15: Async I\u002FO for I\u002FO-Bound Tasks\n\n```python\nimport asyncio\nimport aiohttp\nimport time\nimport requests\n\nurls = [\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n    \"https:\u002F\u002Fhttpbin.org\u002Fdelay\u002F1\",\n]\n\ndef synchronous_requests():\n    \"\"\"Synchronous HTTP requests.\"\"\"\n    start = time.time()\n    results = []\n    for url in urls:\n        response = requests.get(url)\n        results.append(response.status_code)\n    elapsed = time.time() - start\n    return elapsed, results\n\nasync def async_fetch(session, url):\n    \"\"\"Async HTTP request.\"\"\"\n    async with session.get(url) as response:\n        return response.status\n\nasync def asynchronous_requests():\n    \"\"\"Asynchronous HTTP requests.\"\"\"\n    start = time.time()\n    async with aiohttp.ClientSession() as session:\n        tasks = [async_fetch(session, url) for url in urls]\n        results = await asyncio.gather(*tasks)\n    elapsed = time.time() - start\n    return elapsed, results\n\n# Async is much faster for I\u002FO-bound work\nsync_time, sync_results = synchronous_requests()\nasync_time, async_results = asyncio.run(asynchronous_requests())\n\nprint(f\"Synchronous: {sync_time:.2f}s\")\nprint(f\"Asynchronous: {async_time:.2f}s\")\nprint(f\"Speedup: {sync_time\u002Fasync_time:.2f}x\")\n```\n\n## Database Optimization\n\n### Pattern 16: Batch Database Operations\n\n```python\nimport sqlite3\nimport time\n\ndef create_db():\n    \"\"\"Create test database.\"\"\"\n    conn = sqlite3.connect(\":memory:\")\n    conn.execute(\"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)\")\n    return conn\n\ndef slow_inserts(conn, count):\n    \"\"\"Insert records one at a time.\"\"\"\n    start = time.time()\n    cursor = conn.cursor()\n    for i in range(count):\n        cursor.execute(\"INSERT INTO users (name) VALUES (?)\", (f\"User {i}\",))\n        conn.commit()  # Commit each insert\n    elapsed = time.time() - start\n    return elapsed\n\ndef fast_inserts(conn, count):\n    \"\"\"Batch insert with single commit.\"\"\"\n    start = time.time()\n    cursor = conn.cursor()\n    data = [(f\"User {i}\",) for i in range(count)]\n    cursor.executemany(\"INSERT INTO users (name) VALUES (?)\", data)\n    conn.commit()  # Single commit\n    elapsed = time.time() - start\n    return elapsed\n\n# Benchmark\nconn1 = create_db()\nslow_time = slow_inserts(conn1, 1000)\n\nconn2 = create_db()\nfast_time = fast_inserts(conn2, 1000)\n\nprint(f\"Individual inserts: {slow_time:.4f}s\")\nprint(f\"Batch insert: {fast_time:.4f}s\")\nprint(f\"Speedup: {slow_time\u002Ffast_time:.2f}x\")\n```\n\n### Pattern 17: Query Optimization\n\n```python\n# Use indexes for frequently queried columns\n\"\"\"\n-- Slow: No index\nSELECT * FROM users WHERE email = 'user@example.com';\n\n-- Fast: With index\nCREATE INDEX idx_users_email ON users(email);\nSELECT * FROM users WHERE email = 'user@example.com';\n\"\"\"\n\n# Use query planning\nimport sqlite3\n\nconn = sqlite3.connect(\"example.db\")\ncursor = conn.cursor()\n\n# Analyze query performance\ncursor.execute(\"EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = ?\", (\"test@example.com\",))\nprint(cursor.fetchall())\n\n# Use SELECT only needed columns\n# Slow: SELECT *\n# Fast: SELECT id, name\n```\n\n## Memory Optimization\n\n### Pattern 18: Detecting Memory Leaks\n\n```python\nimport tracemalloc\nimport gc\n\ndef memory_leak_example():\n    \"\"\"Example that leaks memory.\"\"\"\n    leaked_objects = []\n\n    for i in range(100000):\n        # Objects added but never removed\n        leaked_objects.append([i] * 100)\n\n    # In real code, this would be an unintended reference\n\ndef track_memory_usage():\n    \"\"\"Track memory allocations.\"\"\"\n    tracemalloc.start()\n\n    # Take snapshot before\n    snapshot1 = tracemalloc.take_snapshot()\n\n    # Run code\n    memory_leak_example()\n\n    # Take snapshot after\n    snapshot2 = tracemalloc.take_snapshot()\n\n    # Compare\n    top_stats = snapshot2.compare_to(snapshot1, 'lineno')\n\n    print(\"Top 10 memory allocations:\")\n    for stat in top_stats[:10]:\n        print(stat)\n\n    tracemalloc.stop()\n\n# Monitor memory\ntrack_memory_usage()\n\n# Force garbage collection\ngc.collect()\n```\n\n### Pattern 19: Iterators vs Lists\n\n```python\nimport sys\n\ndef process_file_list(filename):\n    \"\"\"Load entire file into memory.\"\"\"\n    with open(filename) as f:\n        lines = f.readlines()  # Loads all lines\n        return sum(1 for line in lines if line.strip())\n\ndef process_file_iterator(filename):\n    \"\"\"Process file line by line.\"\"\"\n    with open(filename) as f:\n        return sum(1 for line in f if line.strip())\n\n# Iterator uses constant memory\n# List loads entire file into memory\n```\n\n### Pattern 20: Weakref for Caches\n\n```python\nimport weakref\n\nclass CachedResource:\n    \"\"\"Resource that can be garbage collected.\"\"\"\n    def __init__(self, data):\n        self.data = data\n\n# Regular cache prevents garbage collection\nregular_cache = {}\n\ndef get_resource_regular(key):\n    \"\"\"Get resource from regular cache.\"\"\"\n    if key not in regular_cache:\n        regular_cache[key] = CachedResource(f\"Data for {key}\")\n    return regular_cache[key]\n\n# Weak reference cache allows garbage collection\nweak_cache = weakref.WeakValueDictionary()\n\ndef get_resource_weak(key):\n    \"\"\"Get resource from weak cache.\"\"\"\n    resource = weak_cache.get(key)\n    if resource is None:\n        resource = CachedResource(f\"Data for {key}\")\n        weak_cache[key] = resource\n    return resource\n\n# When no strong references exist, objects can be GC'd\n```\n\n## Benchmarking Tools\n\n### Custom Benchmark Decorator\n\n```python\nimport time\nfrom functools import wraps\n\ndef benchmark(func):\n    \"\"\"Decorator to benchmark function execution.\"\"\"\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.perf_counter()\n        result = func(*args, **kwargs)\n        elapsed = time.perf_counter() - start\n        print(f\"{func.__name__} took {elapsed:.6f} seconds\")\n        return result\n    return wrapper\n\n@benchmark\ndef slow_function():\n    \"\"\"Function to benchmark.\"\"\"\n    time.sleep(0.5)\n    return sum(range(1000000))\n\nresult = slow_function()\n```\n\n### Performance Testing with pytest-benchmark\n\n```python\n# Install: pip install pytest-benchmark\n\ndef test_list_comprehension(benchmark):\n    \"\"\"Benchmark list comprehension.\"\"\"\n    result = benchmark(lambda: [i**2 for i in range(10000)])\n    assert len(result) == 10000\n\ndef test_map_function(benchmark):\n    \"\"\"Benchmark map function.\"\"\"\n    result = benchmark(lambda: list(map(lambda x: x**2, range(10000))))\n    assert len(result) == 10000\n\n# Run with: pytest test_performance.py --benchmark-compare\n```\n\n## Best Practices\n\n1. **Profile before optimizing** - Measure to find real bottlenecks\n2. **Focus on hot paths** - Optimize code that runs most frequently\n3. **Use appropriate data structures** - Dict for lookups, set for membership\n4. **Avoid premature optimization** - Clarity first, then optimize\n5. **Use built-in functions** - They're implemented in C\n6. **Cache expensive computations** - Use lru_cache\n7. **Batch I\u002FO operations** - Reduce system calls\n8. **Use generators** for large datasets\n9. **Consider NumPy** for numerical operations\n10. **Profile production code** - Use py-spy for live systems\n\n## Common Pitfalls\n\n- Optimizing without profiling\n- Using global variables unnecessarily\n- Not using appropriate data structures\n- Creating unnecessary copies of data\n- Not using connection pooling for databases\n- Ignoring algorithmic complexity\n- Over-optimizing rare code paths\n- Not considering memory usage\n\n## Resources\n\n- **cProfile**: Built-in CPU profiler\n- **memory_profiler**: Memory usage profiling\n- **line_profiler**: Line-by-line profiling\n- **py-spy**: Sampling profiler for production\n- **NumPy**: High-performance numerical computing\n- **Cython**: Compile Python to C\n- **PyPy**: Alternative Python interpreter with JIT\n\n## Performance Checklist\n\n- [ ] Profiled code to identify bottlenecks\n- [ ] Used appropriate data structures\n- [ ] Implemented caching where beneficial\n- [ ] Optimized database queries\n- [ ] Used generators for large datasets\n- [ ] Considered multiprocessing for CPU-bound tasks\n- [ ] Used async I\u002FO for I\u002FO-bound tasks\n- [ ] Minimized function call overhead in hot loops\n- [ ] Checked for memory leaks\n- [ ] Benchmarked before and after optimization\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FHarmeet10000\u002Fskills\u002Fpython-performance-optimization",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":47,"prompt":57,"zipAvailable":58},[48,51,54],{"tool":49,"command":50},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill python-performance-optimization",{"tool":52,"command":53},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill python-performance-optimization",{"tool":55,"command":56},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill python-performance-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FHarmeet10000\u002Fskills\u002Fpython-performance-optimization\u002FSKILL.md",true,[60,66,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,156,160,164,168],{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"checklist.md","REFERENCE","参考文档",5656,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fchecklist.md",{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"customize.toml","OTHER","其他",1552,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fcustomize.toml",{"path":73,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":74,"sourceHtmlUrl":75},"data\u002Fcurriculum.yaml",4043,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fdata\u002Fcurriculum.yaml",{"path":77,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":78,"sourceHtmlUrl":79},"data\u002Fquiz-questions.yaml",8370,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fdata\u002Fquiz-questions.yaml",{"path":81,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":82,"sourceHtmlUrl":83},"data\u002Frole-paths.yaml",5305,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fdata\u002Frole-paths.yaml",{"path":85,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":86,"sourceHtmlUrl":87},"data\u002Fsession-content-map.yaml",9489,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fdata\u002Fsession-content-map.yaml",{"path":89,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":90,"sourceHtmlUrl":91},"data\u002Ftea-resources-index.yaml",20401,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fdata\u002Ftea-resources-index.yaml",{"path":93,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":94,"sourceHtmlUrl":95},"instructions.md",4396,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Finstructions.md",{"path":97,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":98,"sourceHtmlUrl":99},"steps-c\u002Fstep-01-init.md",6400,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-01-init.md",{"path":101,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":102,"sourceHtmlUrl":103},"steps-c\u002Fstep-01b-continue.md",4317,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-01b-continue.md",{"path":105,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":106,"sourceHtmlUrl":107},"steps-c\u002Fstep-02-assess.md",7377,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-02-assess.md",{"path":109,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":110,"sourceHtmlUrl":111},"steps-c\u002Fstep-03-session-menu.md",7330,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-03-session-menu.md",{"path":113,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":114,"sourceHtmlUrl":115},"steps-c\u002Fstep-04-session-01.md",15152,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-01.md",{"path":117,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":118,"sourceHtmlUrl":119},"steps-c\u002Fstep-04-session-02.md",13677,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-02.md",{"path":121,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":122,"sourceHtmlUrl":123},"steps-c\u002Fstep-04-session-03.md",7601,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-03.md",{"path":125,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":126,"sourceHtmlUrl":127},"steps-c\u002Fstep-04-session-04.md",6176,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-04.md",{"path":129,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":130,"sourceHtmlUrl":131},"steps-c\u002Fstep-04-session-05.md",5877,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-05.md",{"path":133,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":134,"sourceHtmlUrl":135},"steps-c\u002Fstep-04-session-06.md",5403,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-06.md",{"path":137,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":138,"sourceHtmlUrl":139},"steps-c\u002Fstep-04-session-07.md",7058,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-04-session-07.md",{"path":141,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":142,"sourceHtmlUrl":143},"steps-c\u002Fstep-05-completion.md",9960,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-c\u002Fstep-05-completion.md",{"path":145,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":146,"sourceHtmlUrl":147},"steps-e\u002Fstep-e-01-assess-workflow.md",3363,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-e\u002Fstep-e-01-assess-workflow.md",{"path":149,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":150,"sourceHtmlUrl":151},"steps-e\u002Fstep-e-02-apply-edits.md",3100,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-e\u002Fstep-e-02-apply-edits.md",{"path":153,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":154,"sourceHtmlUrl":155},"steps-v\u002Fstep-v-01-validate.md",6196,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fsteps-v\u002Fstep-v-01-validate.md",{"path":157,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":158,"sourceHtmlUrl":159},"templates\u002Fcertificate-template.md",2416,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Ftemplates\u002Fcertificate-template.md",{"path":161,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":162,"sourceHtmlUrl":163},"templates\u002Fprogress-template.yaml",2266,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Ftemplates\u002Fprogress-template.yaml",{"path":165,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":166,"sourceHtmlUrl":167},"templates\u002Fsession-notes-template.md",1047,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Ftemplates\u002Fsession-notes-template.md",{"path":169,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":170,"sourceHtmlUrl":171},"workflow-plan-teach-me-testing.md",33876,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fbmad-teach-me-testing\u002Fworkflow-plan-teach-me-testing.md",[173,182,191,200,206,212],{"skillNo":174,"name":175,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":178,"publishedAt":32},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[179,180,181],"model","model hierarchy","model hierarchy skill",{"skillNo":183,"name":184,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":187,"publishedAt":32},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[188,189,190],"MCP","zoom","zoom mcp",{"skillNo":192,"name":193,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":196,"publishedAt":32},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[197,198,199,189],"sdk","zoom apps sdk","apps",{"skillNo":201,"name":202,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":203,"categories":204,"keywords":205,"publishedAt":32},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[202],{"skillNo":207,"name":208,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":209,"categories":210,"keywords":211,"publishedAt":32},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[208],{"skillNo":213,"name":214,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":215,"categories":216,"keywords":217,"publishedAt":32},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[214]]