@zimezone/z-command 1.1.1 → 1.1.2

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