[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BWM90YGDYY9ZBZCDWBSKWZ":3,"skill-same:01M7BWM90YGDYY9ZBZCDWBSKWZ":47},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7BWM90YGDYY9ZBZCDWBSKWZ","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.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-performance-optimization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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","# 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",{"name":5,"description":7},"main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-performance-optimization",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-performance-optimization",{"tool":39,"command":40},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-performance-optimization",{"tool":42,"command":43},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill python-performance-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Plugin-插件协议\u002FYYC3-Plugin-插件协议-plugins-claude\u002Fpython-development\u002Fskills\u002Fpython-performance-optimization\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]