playbook/codex/skills/performance-optimization/SKILL.md

114 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
name: performance-optimization
description: "性能优化工作流TSL/Python/C++度量→定位→优化→验证。Triggers: 性能优化, 优化性能, 代码慢, 提升速度, performance optimization, slow code, profiling"
---
# 性能优化工作流
> 适用语言TSL / Python / C++
> 核心原则:没有度量就没有优化。
## 使用时机
- 功能正确,但响应慢或资源消耗过高
- 热路径明显(循环/批处理/大规模数据)
- 需要在不改变行为的前提下提升性能
## 必备输入
- 目标场景与数据规模(输入大小、并发量)
- 基线指标耗时、吞吐、内存、CPU
- 约束条件(允许的改动范围、兼容性要求)
## 工作流程(按顺序)
### 1. 度量基线Baseline
先拿到“优化前”的数据作为对照。
- TSL计时示例使用 MTIC/MTOC
```tsl
T1 := MTIC;
// ... 逻辑 ...
Elapsed := MTOC(T1);
Echo "Elapsed:", Elapsed;
```
- Python
```python
import time
start = time.time()
# ... code ...
print(f"Elapsed: {time.time() - start:.3f}s")
```
- C++
```cpp
auto start = std::chrono::high_resolution_clock::now();
// ... code ...
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - start);
std::cout << "Elapsed: " << elapsed.count() << "ms\n";
```
### 2. 定位瓶颈Profiling
只优化热点,不动冷路径。
- TSL插入关键路径计时或使用 `docs/tsl/syntax_book/07_debug_and_profiler.md` 中的工具
- Python`cProfile` / `line_profiler`
- C++`perf` / `gprof` / `valgrind --tool=callgrind`
### 3. 优化策略(从高收益到低收益)
**3.1 算法级(优先级最高)**
- 降低复杂度:`O(n^2)` → `O(n log n)``O(n)`
- 避免重复计算:缓存、记忆化
**3.2 数据结构级**
- 选择合适容器:数组 vs 哈希表 vs 树
- 预分配容量,减少扩容
**3.3 循环级**
- 循环内不做 I/O
- 循环内避免重复解析/格式化
- 提前计算循环不变量
**3.4 I/O 级**
- 批量读写(减少系统调用)
- 缓存(明确 TTL 与容量上限)
### 4. 验证效果Verify
- 对比优化前后指标
- 运行回归测试,保证行为一致
- 在真实数据量下复测
## 反模式(不要做)
- 没有度量就“感觉”优化
- 牺牲可读性换取微小收益
- 为冷路径引入复杂缓存
- 未验证就宣称提升
## 输出清单(交付要求)
- 基线指标(优化前)
- 瓶颈定位结果(热点函数/路径)
- 优化方案与改动点
- 优化后指标(对比数据)
- 风险说明与回滚策略
## 权威参考
- TSL`docs/tsl/syntax_book/07_debug_and_profiler.md`
- Python`docs/python/tooling.md`
- C++`docs/cpp/toolchain.md`