@sylix/coworker 2.0.11 → 2.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/dist/commands/slash/config.d.ts.map +1 -1
  2. package/dist/commands/slash/config.js +22 -4
  3. package/dist/commands/slash/config.js.map +1 -1
  4. package/dist/core/CoWorkerAgent.d.ts.map +1 -1
  5. package/dist/core/CoWorkerAgent.js +6 -3
  6. package/dist/core/CoWorkerAgent.js.map +1 -1
  7. package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
  8. package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
  9. package/dist/skills/defaults/ai-ml/rag.md +276 -0
  10. package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
  11. package/dist/skills/defaults/backend-development/api-design.md +285 -0
  12. package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
  13. package/dist/skills/defaults/backend-development/async-python.md +237 -0
  14. package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
  15. package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
  16. package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
  17. package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
  18. package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
  19. package/dist/skills/defaults/backend-development/database-design.md +305 -0
  20. package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
  21. package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
  22. package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
  23. package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
  24. package/dist/skills/defaults/backend-development/fastapi.md +309 -0
  25. package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
  26. package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
  27. package/dist/skills/defaults/backend-development/microservices.md +284 -0
  28. package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
  29. package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
  30. package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
  31. package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
  32. package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
  33. package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
  34. package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
  35. package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
  36. package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
  37. package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
  38. package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
  39. package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
  40. package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
  41. package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
  42. package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
  43. package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
  44. package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
  45. package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
  46. package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
  47. package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
  48. package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
  49. package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
  50. package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
  51. package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
  52. package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
  53. package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
  54. package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
  55. package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
  56. package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
  57. package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
  58. package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
  59. package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
  60. package/dist/skills/defaults/data-engineering/airflow.md +519 -0
  61. package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
  62. package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
  63. package/dist/skills/defaults/data-engineering/dbt.md +556 -0
  64. package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
  65. package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
  66. package/dist/skills/defaults/data-engineering/spark.md +411 -0
  67. package/dist/skills/defaults/database/postgresql.md +202 -0
  68. package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
  69. package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
  70. package/dist/skills/defaults/devops/changelog-automation.md +580 -0
  71. package/dist/skills/defaults/devops/cicd.md +314 -0
  72. package/dist/skills/defaults/devops/cloud.md +263 -0
  73. package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
  74. package/dist/skills/defaults/devops/cost-optimization.md +295 -0
  75. package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
  76. package/dist/skills/defaults/devops/docker.md +281 -0
  77. package/dist/skills/defaults/devops/git-workflows.md +205 -0
  78. package/dist/skills/defaults/devops/github-actions.md +311 -0
  79. package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
  80. package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
  81. package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
  82. package/dist/skills/defaults/devops/kubernetes.md +339 -0
  83. package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
  84. package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
  85. package/dist/skills/defaults/devops/observability.md +243 -0
  86. package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
  87. package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
  88. package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
  89. package/dist/skills/defaults/devops/secrets-management.md +341 -0
  90. package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
  91. package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
  92. package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
  93. package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
  94. package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
  95. package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
  96. package/dist/skills/defaults/frontend/interaction-design.md +327 -0
  97. package/dist/skills/defaults/frontend/javascript.md +311 -0
  98. package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
  99. package/dist/skills/defaults/frontend/react-native-design.md +440 -0
  100. package/dist/skills/defaults/frontend/react.md +345 -0
  101. package/dist/skills/defaults/frontend/responsive-design.md +472 -0
  102. package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
  103. package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
  104. package/dist/skills/defaults/frontend/typescript.md +334 -0
  105. package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
  106. package/dist/skills/defaults/frontend/web-component-design.md +279 -0
  107. package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
  108. package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
  109. package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
  110. package/dist/skills/defaults/kubernetes/gitops.md +280 -0
  111. package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
  112. package/dist/skills/defaults/kubernetes/helm.md +343 -0
  113. package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
  114. package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
  115. package/dist/skills/defaults/kubernetes/manifests.md +330 -0
  116. package/dist/skills/defaults/kubernetes/security.md +337 -0
  117. package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
  118. package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
  119. package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
  120. package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
  121. package/dist/skills/defaults/llm-application/langchain.md +259 -0
  122. package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
  123. package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
  124. package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
  125. package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
  126. package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
  127. package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
  128. package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
  129. package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
  130. package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
  131. package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
  132. package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
  133. package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
  134. package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
  135. package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
  136. package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
  137. package/dist/skills/defaults/security/auditor.md +168 -0
  138. package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
  139. package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
  140. package/dist/skills/defaults/security/mtls-configuration.md +349 -0
  141. package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
  142. package/dist/skills/defaults/security/sast-configuration.md +182 -0
  143. package/dist/skills/defaults/security/security.md +313 -0
  144. package/dist/skills/defaults/security/stride-analysis.md +273 -0
  145. package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
  146. package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
  147. package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
  148. package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
  149. package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
  150. package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
  151. package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
  152. package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
  153. package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
  154. package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
  155. package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
  156. package/dist/skills/defaults/testing/testing.md +332 -0
  157. package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
  158. package/dist/skills/defaults/workflows/track-management.md +592 -0
  159. package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
  160. package/dist/skills/index.d.ts +11 -0
  161. package/dist/skills/index.d.ts.map +1 -0
  162. package/dist/skills/index.js +129 -0
  163. package/dist/skills/index.js.map +1 -0
  164. package/dist/utils/character.js +4 -4
  165. package/dist/utils/character.js.map +1 -1
  166. package/dist/utils/inputbar.d.ts.map +1 -1
  167. package/dist/utils/inputbar.js +7 -0
  168. package/dist/utils/inputbar.js.map +1 -1
  169. package/package.json +1 -1
@@ -0,0 +1,874 @@
1
+ ---
2
+ name: python-performance-optimization
3
+ description: Profile and optimize Python code using cProfile, memory profilers, and performance best practices. Use when debugging slow Python code, optimizing bottlenecks, or improving application performance.
4
+ ---
5
+
6
+ # Python Performance Optimization
7
+
8
+ Comprehensive guide to profiling, analyzing, and optimizing Python code for better performance, including CPU profiling, memory optimization, and implementation best practices.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Identifying performance bottlenecks in Python applications
13
+ - Reducing application latency and response times
14
+ - Optimizing CPU-intensive operations
15
+ - Reducing memory consumption and memory leaks
16
+ - Improving database query performance
17
+ - Optimizing I/O operations
18
+ - Speeding up data processing pipelines
19
+ - Implementing high-performance algorithms
20
+ - Profiling production applications
21
+
22
+ ## Core Concepts
23
+
24
+ ### 1. Profiling Types
25
+
26
+ - **CPU Profiling**: Identify time-consuming functions
27
+ - **Memory Profiling**: Track memory allocation and leaks
28
+ - **Line Profiling**: Profile at line-by-line granularity
29
+ - **Call Graph**: Visualize function call relationships
30
+
31
+ ### 2. Performance Metrics
32
+
33
+ - **Execution Time**: How long operations take
34
+ - **Memory Usage**: Peak and average memory consumption
35
+ - **CPU Utilization**: Processor usage patterns
36
+ - **I/O Wait**: Time spent on I/O operations
37
+
38
+ ### 3. Optimization Strategies
39
+
40
+ - **Algorithmic**: Better algorithms and data structures
41
+ - **Implementation**: More efficient code patterns
42
+ - **Parallelization**: Multi-threading/processing
43
+ - **Caching**: Avoid redundant computation
44
+ - **Native Extensions**: C/Rust for critical paths
45
+
46
+ ## Quick Start
47
+
48
+ ### Basic Timing
49
+
50
+ ```python
51
+ import time
52
+
53
+ def measure_time():
54
+ """Simple timing measurement."""
55
+ start = time.time()
56
+
57
+ # Your code here
58
+ result = sum(range(1000000))
59
+
60
+ elapsed = time.time() - start
61
+ print(f"Execution time: {elapsed:.4f} seconds")
62
+ return result
63
+
64
+ # Better: use timeit for accurate measurements
65
+ import timeit
66
+
67
+ execution_time = timeit.timeit(
68
+ "sum(range(1000000))",
69
+ number=100
70
+ )
71
+ print(f"Average time: {execution_time/100:.6f} seconds")
72
+ ```
73
+
74
+ ## Profiling Tools
75
+
76
+ ### Pattern 1: cProfile - CPU Profiling
77
+
78
+ ```python
79
+ import cProfile
80
+ import pstats
81
+ from pstats import SortKey
82
+
83
+ def slow_function():
84
+ """Function to profile."""
85
+ total = 0
86
+ for i in range(1000000):
87
+ total += i
88
+ return total
89
+
90
+ def another_function():
91
+ """Another function."""
92
+ return [i**2 for i in range(100000)]
93
+
94
+ def main():
95
+ """Main function to profile."""
96
+ result1 = slow_function()
97
+ result2 = another_function()
98
+ return result1, result2
99
+
100
+ # Profile the code
101
+ if __name__ == "__main__":
102
+ profiler = cProfile.Profile()
103
+ profiler.enable()
104
+
105
+ main()
106
+
107
+ profiler.disable()
108
+
109
+ # Print stats
110
+ stats = pstats.Stats(profiler)
111
+ stats.sort_stats(SortKey.CUMULATIVE)
112
+ stats.print_stats(10) # Top 10 functions
113
+
114
+ # Save to file for later analysis
115
+ stats.dump_stats("profile_output.prof")
116
+ ```
117
+
118
+ **Command-line profiling:**
119
+
120
+ ```bash
121
+ # Profile a script
122
+ python -m cProfile -o output.prof script.py
123
+
124
+ # View results
125
+ python -m pstats output.prof
126
+ # In pstats:
127
+ # sort cumtime
128
+ # stats 10
129
+ ```
130
+
131
+ ### Pattern 2: line_profiler - Line-by-Line Profiling
132
+
133
+ ```python
134
+ # Install: pip install line-profiler
135
+
136
+ # Add @profile decorator (line_profiler provides this)
137
+ @profile
138
+ def process_data(data):
139
+ """Process data with line profiling."""
140
+ result = []
141
+ for item in data:
142
+ processed = item * 2
143
+ result.append(processed)
144
+ return result
145
+
146
+ # Run with:
147
+ # kernprof -l -v script.py
148
+ ```
149
+
150
+ **Manual line profiling:**
151
+
152
+ ```python
153
+ from line_profiler import LineProfiler
154
+
155
+ def process_data(data):
156
+ """Function to profile."""
157
+ result = []
158
+ for item in data:
159
+ processed = item * 2
160
+ result.append(processed)
161
+ return result
162
+
163
+ if __name__ == "__main__":
164
+ lp = LineProfiler()
165
+ lp.add_function(process_data)
166
+
167
+ data = list(range(100000))
168
+
169
+ lp_wrapper = lp(process_data)
170
+ lp_wrapper(data)
171
+
172
+ lp.print_stats()
173
+ ```
174
+
175
+ ### Pattern 3: memory_profiler - Memory Usage
176
+
177
+ ```python
178
+ # Install: pip install memory-profiler
179
+
180
+ from memory_profiler import profile
181
+
182
+ @profile
183
+ def memory_intensive():
184
+ """Function that uses lots of memory."""
185
+ # Create large list
186
+ big_list = [i for i in range(1000000)]
187
+
188
+ # Create large dict
189
+ big_dict = {i: i**2 for i in range(100000)}
190
+
191
+ # Process data
192
+ result = sum(big_list)
193
+
194
+ return result
195
+
196
+ if __name__ == "__main__":
197
+ memory_intensive()
198
+
199
+ # Run with:
200
+ # python -m memory_profiler script.py
201
+ ```
202
+
203
+ ### Pattern 4: py-spy - Production Profiling
204
+
205
+ ```bash
206
+ # Install: pip install py-spy
207
+
208
+ # Profile a running Python process
209
+ py-spy top --pid 12345
210
+
211
+ # Generate flamegraph
212
+ py-spy record -o profile.svg --pid 12345
213
+
214
+ # Profile a script
215
+ py-spy record -o profile.svg -- python script.py
216
+
217
+ # Dump current call stack
218
+ py-spy dump --pid 12345
219
+ ```
220
+
221
+ ## Optimization Patterns
222
+
223
+ ### Pattern 5: List Comprehensions vs Loops
224
+
225
+ ```python
226
+ import timeit
227
+
228
+ # Slow: Traditional loop
229
+ def slow_squares(n):
230
+ """Create list of squares using loop."""
231
+ result = []
232
+ for i in range(n):
233
+ result.append(i**2)
234
+ return result
235
+
236
+ # Fast: List comprehension
237
+ def fast_squares(n):
238
+ """Create list of squares using comprehension."""
239
+ return [i**2 for i in range(n)]
240
+
241
+ # Benchmark
242
+ n = 100000
243
+
244
+ slow_time = timeit.timeit(lambda: slow_squares(n), number=100)
245
+ fast_time = timeit.timeit(lambda: fast_squares(n), number=100)
246
+
247
+ print(f"Loop: {slow_time:.4f}s")
248
+ print(f"Comprehension: {fast_time:.4f}s")
249
+ print(f"Speedup: {slow_time/fast_time:.2f}x")
250
+
251
+ # Even faster for simple operations: map
252
+ def faster_squares(n):
253
+ """Use map for even better performance."""
254
+ return list(map(lambda x: x**2, range(n)))
255
+ ```
256
+
257
+ ### Pattern 6: Generator Expressions for Memory
258
+
259
+ ```python
260
+ import sys
261
+
262
+ def list_approach():
263
+ """Memory-intensive list."""
264
+ data = [i**2 for i in range(1000000)]
265
+ return sum(data)
266
+
267
+ def generator_approach():
268
+ """Memory-efficient generator."""
269
+ data = (i**2 for i in range(1000000))
270
+ return sum(data)
271
+
272
+ # Memory comparison
273
+ list_data = [i for i in range(1000000)]
274
+ gen_data = (i for i in range(1000000))
275
+
276
+ print(f"List size: {sys.getsizeof(list_data)} bytes")
277
+ print(f"Generator size: {sys.getsizeof(gen_data)} bytes")
278
+
279
+ # Generators use constant memory regardless of size
280
+ ```
281
+
282
+ ### Pattern 7: String Concatenation
283
+
284
+ ```python
285
+ import timeit
286
+
287
+ def slow_concat(items):
288
+ """Slow string concatenation."""
289
+ result = ""
290
+ for item in items:
291
+ result += str(item)
292
+ return result
293
+
294
+ def fast_concat(items):
295
+ """Fast string concatenation with join."""
296
+ return "".join(str(item) for item in items)
297
+
298
+ def faster_concat(items):
299
+ """Even faster with list."""
300
+ parts = [str(item) for item in items]
301
+ return "".join(parts)
302
+
303
+ items = list(range(10000))
304
+
305
+ # Benchmark
306
+ slow = timeit.timeit(lambda: slow_concat(items), number=100)
307
+ fast = timeit.timeit(lambda: fast_concat(items), number=100)
308
+ faster = timeit.timeit(lambda: faster_concat(items), number=100)
309
+
310
+ print(f"Concatenation (+): {slow:.4f}s")
311
+ print(f"Join (generator): {fast:.4f}s")
312
+ print(f"Join (list): {faster:.4f}s")
313
+ ```
314
+
315
+ ### Pattern 8: Dictionary Lookups vs List Searches
316
+
317
+ ```python
318
+ import timeit
319
+
320
+ # Create test data
321
+ size = 10000
322
+ items = list(range(size))
323
+ lookup_dict = {i: i for i in range(size)}
324
+
325
+ def list_search(items, target):
326
+ """O(n) search in list."""
327
+ return target in items
328
+
329
+ def dict_search(lookup_dict, target):
330
+ """O(1) search in dict."""
331
+ return target in lookup_dict
332
+
333
+ target = size - 1 # Worst case for list
334
+
335
+ # Benchmark
336
+ list_time = timeit.timeit(
337
+ lambda: list_search(items, target),
338
+ number=1000
339
+ )
340
+ dict_time = timeit.timeit(
341
+ lambda: dict_search(lookup_dict, target),
342
+ number=1000
343
+ )
344
+
345
+ print(f"List search: {list_time:.6f}s")
346
+ print(f"Dict search: {dict_time:.6f}s")
347
+ print(f"Speedup: {list_time/dict_time:.0f}x")
348
+ ```
349
+
350
+ ### Pattern 9: Local Variable Access
351
+
352
+ ```python
353
+ import timeit
354
+
355
+ # Global variable (slow)
356
+ GLOBAL_VALUE = 100
357
+
358
+ def use_global():
359
+ """Access global variable."""
360
+ total = 0
361
+ for i in range(10000):
362
+ total += GLOBAL_VALUE
363
+ return total
364
+
365
+ def use_local():
366
+ """Use local variable."""
367
+ local_value = 100
368
+ total = 0
369
+ for i in range(10000):
370
+ total += local_value
371
+ return total
372
+
373
+ # Local is faster
374
+ global_time = timeit.timeit(use_global, number=1000)
375
+ local_time = timeit.timeit(use_local, number=1000)
376
+
377
+ print(f"Global access: {global_time:.4f}s")
378
+ print(f"Local access: {local_time:.4f}s")
379
+ print(f"Speedup: {global_time/local_time:.2f}x")
380
+ ```
381
+
382
+ ### Pattern 10: Function Call Overhead
383
+
384
+ ```python
385
+ import timeit
386
+
387
+ def calculate_inline():
388
+ """Inline calculation."""
389
+ total = 0
390
+ for i in range(10000):
391
+ total += i * 2 + 1
392
+ return total
393
+
394
+ def helper_function(x):
395
+ """Helper function."""
396
+ return x * 2 + 1
397
+
398
+ def calculate_with_function():
399
+ """Calculation with function calls."""
400
+ total = 0
401
+ for i in range(10000):
402
+ total += helper_function(i)
403
+ return total
404
+
405
+ # Inline is faster due to no call overhead
406
+ inline_time = timeit.timeit(calculate_inline, number=1000)
407
+ function_time = timeit.timeit(calculate_with_function, number=1000)
408
+
409
+ print(f"Inline: {inline_time:.4f}s")
410
+ print(f"Function calls: {function_time:.4f}s")
411
+ ```
412
+
413
+ ## Advanced Optimization
414
+
415
+ ### Pattern 11: NumPy for Numerical Operations
416
+
417
+ ```python
418
+ import timeit
419
+ import numpy as np
420
+
421
+ def python_sum(n):
422
+ """Sum using pure Python."""
423
+ return sum(range(n))
424
+
425
+ def numpy_sum(n):
426
+ """Sum using NumPy."""
427
+ return np.arange(n).sum()
428
+
429
+ n = 1000000
430
+
431
+ python_time = timeit.timeit(lambda: python_sum(n), number=100)
432
+ numpy_time = timeit.timeit(lambda: numpy_sum(n), number=100)
433
+
434
+ print(f"Python: {python_time:.4f}s")
435
+ print(f"NumPy: {numpy_time:.4f}s")
436
+ print(f"Speedup: {python_time/numpy_time:.2f}x")
437
+
438
+ # Vectorized operations
439
+ def python_multiply():
440
+ """Element-wise multiplication in Python."""
441
+ a = list(range(100000))
442
+ b = list(range(100000))
443
+ return [x * y for x, y in zip(a, b)]
444
+
445
+ def numpy_multiply():
446
+ """Vectorized multiplication in NumPy."""
447
+ a = np.arange(100000)
448
+ b = np.arange(100000)
449
+ return a * b
450
+
451
+ py_time = timeit.timeit(python_multiply, number=100)
452
+ np_time = timeit.timeit(numpy_multiply, number=100)
453
+
454
+ print(f"\nPython multiply: {py_time:.4f}s")
455
+ print(f"NumPy multiply: {np_time:.4f}s")
456
+ print(f"Speedup: {py_time/np_time:.2f}x")
457
+ ```
458
+
459
+ ### Pattern 12: Caching with functools.lru_cache
460
+
461
+ ```python
462
+ from functools import lru_cache
463
+ import timeit
464
+
465
+ def fibonacci_slow(n):
466
+ """Recursive fibonacci without caching."""
467
+ if n < 2:
468
+ return n
469
+ return fibonacci_slow(n-1) + fibonacci_slow(n-2)
470
+
471
+ @lru_cache(maxsize=None)
472
+ def fibonacci_fast(n):
473
+ """Recursive fibonacci with caching."""
474
+ if n < 2:
475
+ return n
476
+ return fibonacci_fast(n-1) + fibonacci_fast(n-2)
477
+
478
+ # Massive speedup for recursive algorithms
479
+ n = 30
480
+
481
+ slow_time = timeit.timeit(lambda: fibonacci_slow(n), number=1)
482
+ fast_time = timeit.timeit(lambda: fibonacci_fast(n), number=1000)
483
+
484
+ print(f"Without cache (1 run): {slow_time:.4f}s")
485
+ print(f"With cache (1000 runs): {fast_time:.4f}s")
486
+
487
+ # Cache info
488
+ print(f"Cache info: {fibonacci_fast.cache_info()}")
489
+ ```
490
+
491
+ ### Pattern 13: Using __slots__ for Memory
492
+
493
+ ```python
494
+ import sys
495
+
496
+ class RegularClass:
497
+ """Regular class with __dict__."""
498
+ def __init__(self, x, y, z):
499
+ self.x = x
500
+ self.y = y
501
+ self.z = z
502
+
503
+ class SlottedClass:
504
+ """Class with __slots__ for memory efficiency."""
505
+ __slots__ = ['x', 'y', 'z']
506
+
507
+ def __init__(self, x, y, z):
508
+ self.x = x
509
+ self.y = y
510
+ self.z = z
511
+
512
+ # Memory comparison
513
+ regular = RegularClass(1, 2, 3)
514
+ slotted = SlottedClass(1, 2, 3)
515
+
516
+ print(f"Regular class size: {sys.getsizeof(regular)} bytes")
517
+ print(f"Slotted class size: {sys.getsizeof(slotted)} bytes")
518
+
519
+ # Significant savings with many instances
520
+ regular_objects = [RegularClass(i, i+1, i+2) for i in range(10000)]
521
+ slotted_objects = [SlottedClass(i, i+1, i+2) for i in range(10000)]
522
+
523
+ print(f"\nMemory for 10000 regular objects: ~{sys.getsizeof(regular) * 10000} bytes")
524
+ print(f"Memory for 10000 slotted objects: ~{sys.getsizeof(slotted) * 10000} bytes")
525
+ ```
526
+
527
+ ### Pattern 14: Multiprocessing for CPU-Bound Tasks
528
+
529
+ ```python
530
+ import multiprocessing as mp
531
+ import time
532
+
533
+ def cpu_intensive_task(n):
534
+ """CPU-intensive calculation."""
535
+ return sum(i**2 for i in range(n))
536
+
537
+ def sequential_processing():
538
+ """Process tasks sequentially."""
539
+ start = time.time()
540
+ results = [cpu_intensive_task(1000000) for _ in range(4)]
541
+ elapsed = time.time() - start
542
+ return elapsed, results
543
+
544
+ def parallel_processing():
545
+ """Process tasks in parallel."""
546
+ start = time.time()
547
+ with mp.Pool(processes=4) as pool:
548
+ results = pool.map(cpu_intensive_task, [1000000] * 4)
549
+ elapsed = time.time() - start
550
+ return elapsed, results
551
+
552
+ if __name__ == "__main__":
553
+ seq_time, seq_results = sequential_processing()
554
+ par_time, par_results = parallel_processing()
555
+
556
+ print(f"Sequential: {seq_time:.2f}s")
557
+ print(f"Parallel: {par_time:.2f}s")
558
+ print(f"Speedup: {seq_time/par_time:.2f}x")
559
+ ```
560
+
561
+ ### Pattern 15: Async I/O for I/O-Bound Tasks
562
+
563
+ ```python
564
+ import asyncio
565
+ import aiohttp
566
+ import time
567
+ import requests
568
+
569
+ urls = [
570
+ "https://httpbin.org/delay/1",
571
+ "https://httpbin.org/delay/1",
572
+ "https://httpbin.org/delay/1",
573
+ "https://httpbin.org/delay/1",
574
+ ]
575
+
576
+ def synchronous_requests():
577
+ """Synchronous HTTP requests."""
578
+ start = time.time()
579
+ results = []
580
+ for url in urls:
581
+ response = requests.get(url)
582
+ results.append(response.status_code)
583
+ elapsed = time.time() - start
584
+ return elapsed, results
585
+
586
+ async def async_fetch(session, url):
587
+ """Async HTTP request."""
588
+ async with session.get(url) as response:
589
+ return response.status
590
+
591
+ async def asynchronous_requests():
592
+ """Asynchronous HTTP requests."""
593
+ start = time.time()
594
+ async with aiohttp.ClientSession() as session:
595
+ tasks = [async_fetch(session, url) for url in urls]
596
+ results = await asyncio.gather(*tasks)
597
+ elapsed = time.time() - start
598
+ return elapsed, results
599
+
600
+ # Async is much faster for I/O-bound work
601
+ sync_time, sync_results = synchronous_requests()
602
+ async_time, async_results = asyncio.run(asynchronous_requests())
603
+
604
+ print(f"Synchronous: {sync_time:.2f}s")
605
+ print(f"Asynchronous: {async_time:.2f}s")
606
+ print(f"Speedup: {sync_time/async_time:.2f}x")
607
+ ```
608
+
609
+ ## Database Optimization
610
+
611
+ ### Pattern 16: Batch Database Operations
612
+
613
+ ```python
614
+ import sqlite3
615
+ import time
616
+
617
+ def create_db():
618
+ """Create test database."""
619
+ conn = sqlite3.connect(":memory:")
620
+ conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
621
+ return conn
622
+
623
+ def slow_inserts(conn, count):
624
+ """Insert records one at a time."""
625
+ start = time.time()
626
+ cursor = conn.cursor()
627
+ for i in range(count):
628
+ cursor.execute("INSERT INTO users (name) VALUES (?)", (f"User {i}",))
629
+ conn.commit() # Commit each insert
630
+ elapsed = time.time() - start
631
+ return elapsed
632
+
633
+ def fast_inserts(conn, count):
634
+ """Batch insert with single commit."""
635
+ start = time.time()
636
+ cursor = conn.cursor()
637
+ data = [(f"User {i}",) for i in range(count)]
638
+ cursor.executemany("INSERT INTO users (name) VALUES (?)", data)
639
+ conn.commit() # Single commit
640
+ elapsed = time.time() - start
641
+ return elapsed
642
+
643
+ # Benchmark
644
+ conn1 = create_db()
645
+ slow_time = slow_inserts(conn1, 1000)
646
+
647
+ conn2 = create_db()
648
+ fast_time = fast_inserts(conn2, 1000)
649
+
650
+ print(f"Individual inserts: {slow_time:.4f}s")
651
+ print(f"Batch insert: {fast_time:.4f}s")
652
+ print(f"Speedup: {slow_time/fast_time:.2f}x")
653
+ ```
654
+
655
+ ### Pattern 17: Query Optimization
656
+
657
+ ```python
658
+ # Use indexes for frequently queried columns
659
+ """
660
+ -- Slow: No index
661
+ SELECT * FROM users WHERE email = 'user@example.com';
662
+
663
+ -- Fast: With index
664
+ CREATE INDEX idx_users_email ON users(email);
665
+ SELECT * FROM users WHERE email = 'user@example.com';
666
+ """
667
+
668
+ # Use query planning
669
+ import sqlite3
670
+
671
+ conn = sqlite3.connect("example.db")
672
+ cursor = conn.cursor()
673
+
674
+ # Analyze query performance
675
+ cursor.execute("EXPLAIN QUERY PLAN SELECT * FROM users WHERE email = ?", ("test@example.com",))
676
+ print(cursor.fetchall())
677
+
678
+ # Use SELECT only needed columns
679
+ # Slow: SELECT *
680
+ # Fast: SELECT id, name
681
+ ```
682
+
683
+ ## Memory Optimization
684
+
685
+ ### Pattern 18: Detecting Memory Leaks
686
+
687
+ ```python
688
+ import tracemalloc
689
+ import gc
690
+
691
+ def memory_leak_example():
692
+ """Example that leaks memory."""
693
+ leaked_objects = []
694
+
695
+ for i in range(100000):
696
+ # Objects added but never removed
697
+ leaked_objects.append([i] * 100)
698
+
699
+ # In real code, this would be an unintended reference
700
+
701
+ def track_memory_usage():
702
+ """Track memory allocations."""
703
+ tracemalloc.start()
704
+
705
+ # Take snapshot before
706
+ snapshot1 = tracemalloc.take_snapshot()
707
+
708
+ # Run code
709
+ memory_leak_example()
710
+
711
+ # Take snapshot after
712
+ snapshot2 = tracemalloc.take_snapshot()
713
+
714
+ # Compare
715
+ top_stats = snapshot2.compare_to(snapshot1, 'lineno')
716
+
717
+ print("Top 10 memory allocations:")
718
+ for stat in top_stats[:10]:
719
+ print(stat)
720
+
721
+ tracemalloc.stop()
722
+
723
+ # Monitor memory
724
+ track_memory_usage()
725
+
726
+ # Force garbage collection
727
+ gc.collect()
728
+ ```
729
+
730
+ ### Pattern 19: Iterators vs Lists
731
+
732
+ ```python
733
+ import sys
734
+
735
+ def process_file_list(filename):
736
+ """Load entire file into memory."""
737
+ with open(filename) as f:
738
+ lines = f.readlines() # Loads all lines
739
+ return sum(1 for line in lines if line.strip())
740
+
741
+ def process_file_iterator(filename):
742
+ """Process file line by line."""
743
+ with open(filename) as f:
744
+ return sum(1 for line in f if line.strip())
745
+
746
+ # Iterator uses constant memory
747
+ # List loads entire file into memory
748
+ ```
749
+
750
+ ### Pattern 20: Weakref for Caches
751
+
752
+ ```python
753
+ import weakref
754
+
755
+ class CachedResource:
756
+ """Resource that can be garbage collected."""
757
+ def __init__(self, data):
758
+ self.data = data
759
+
760
+ # Regular cache prevents garbage collection
761
+ regular_cache = {}
762
+
763
+ def get_resource_regular(key):
764
+ """Get resource from regular cache."""
765
+ if key not in regular_cache:
766
+ regular_cache[key] = CachedResource(f"Data for {key}")
767
+ return regular_cache[key]
768
+
769
+ # Weak reference cache allows garbage collection
770
+ weak_cache = weakref.WeakValueDictionary()
771
+
772
+ def get_resource_weak(key):
773
+ """Get resource from weak cache."""
774
+ resource = weak_cache.get(key)
775
+ if resource is None:
776
+ resource = CachedResource(f"Data for {key}")
777
+ weak_cache[key] = resource
778
+ return resource
779
+
780
+ # When no strong references exist, objects can be GC'd
781
+ ```
782
+
783
+ ## Benchmarking Tools
784
+
785
+ ### Custom Benchmark Decorator
786
+
787
+ ```python
788
+ import time
789
+ from functools import wraps
790
+
791
+ def benchmark(func):
792
+ """Decorator to benchmark function execution."""
793
+ @wraps(func)
794
+ def wrapper(*args, **kwargs):
795
+ start = time.perf_counter()
796
+ result = func(*args, **kwargs)
797
+ elapsed = time.perf_counter() - start
798
+ print(f"{func.__name__} took {elapsed:.6f} seconds")
799
+ return result
800
+ return wrapper
801
+
802
+ @benchmark
803
+ def slow_function():
804
+ """Function to benchmark."""
805
+ time.sleep(0.5)
806
+ return sum(range(1000000))
807
+
808
+ result = slow_function()
809
+ ```
810
+
811
+ ### Performance Testing with pytest-benchmark
812
+
813
+ ```python
814
+ # Install: pip install pytest-benchmark
815
+
816
+ def test_list_comprehension(benchmark):
817
+ """Benchmark list comprehension."""
818
+ result = benchmark(lambda: [i**2 for i in range(10000)])
819
+ assert len(result) == 10000
820
+
821
+ def test_map_function(benchmark):
822
+ """Benchmark map function."""
823
+ result = benchmark(lambda: list(map(lambda x: x**2, range(10000))))
824
+ assert len(result) == 10000
825
+
826
+ # Run with: pytest test_performance.py --benchmark-compare
827
+ ```
828
+
829
+ ## Best Practices
830
+
831
+ 1. **Profile before optimizing** - Measure to find real bottlenecks
832
+ 2. **Focus on hot paths** - Optimize code that runs most frequently
833
+ 3. **Use appropriate data structures** - Dict for lookups, set for membership
834
+ 4. **Avoid premature optimization** - Clarity first, then optimize
835
+ 5. **Use built-in functions** - They're implemented in C
836
+ 6. **Cache expensive computations** - Use lru_cache
837
+ 7. **Batch I/O operations** - Reduce system calls
838
+ 8. **Use generators** for large datasets
839
+ 9. **Consider NumPy** for numerical operations
840
+ 10. **Profile production code** - Use py-spy for live systems
841
+
842
+ ## Common Pitfalls
843
+
844
+ - Optimizing without profiling
845
+ - Using global variables unnecessarily
846
+ - Not using appropriate data structures
847
+ - Creating unnecessary copies of data
848
+ - Not using connection pooling for databases
849
+ - Ignoring algorithmic complexity
850
+ - Over-optimizing rare code paths
851
+ - Not considering memory usage
852
+
853
+ ## Resources
854
+
855
+ - **cProfile**: Built-in CPU profiler
856
+ - **memory_profiler**: Memory usage profiling
857
+ - **line_profiler**: Line-by-line profiling
858
+ - **py-spy**: Sampling profiler for production
859
+ - **NumPy**: High-performance numerical computing
860
+ - **Cython**: Compile Python to C
861
+ - **PyPy**: Alternative Python interpreter with JIT
862
+
863
+ ## Performance Checklist
864
+
865
+ - [ ] Profiled code to identify bottlenecks
866
+ - [ ] Used appropriate data structures
867
+ - [ ] Implemented caching where beneficial
868
+ - [ ] Optimized database queries
869
+ - [ ] Used generators for large datasets
870
+ - [ ] Considered multiprocessing for CPU-bound tasks
871
+ - [ ] Used async I/O for I/O-bound tasks
872
+ - [ ] Minimized function call overhead in hot loops
873
+ - [ ] Checked for memory leaks
874
+ - [ ] Benchmarked before and after optimization