Files
iAOP/templates/ti-cl4/perf-budget/README.md
T

54 lines
2.5 KiB
Markdown
Raw Normal View History

# 性能预算与懒加载策略引擎(Issue #54 / PRD 5.5)
> 父 Issue「⑤ 性能优化(首屏 ≤ 2s,图表懒加载)· 0.5d」
把驾驶舱性能口径落为**可校验、可测试的纯标准库引擎**(无 node/前端构建环境,
与 iAOP 零运行时依赖原则一致)。产出两类资产:
## 1. 性能预算与校验(`perf_budget.py`)
- `PerformanceBudget` —— 首屏预算(默认 ≤ 2000ms,PRD 5.5)+ 分资源类型预算
(HTML/CSS/JS/字体/接口/图片)。`PerformanceBudget.default_cockpit()` 给驾驶舱默认预算。
- `ResourceMeasurement` —— 单资源实测耗时(含 `block_render` 标记,区分关键路径)。
- `BudgetVerifier` —— 校验器:按**关键路径口径**(阻塞渲染资源串行累加、非阻塞并行取最大)
计算首屏总耗时,逐类型比对预算,产出 `BudgetReport`(状态 PASS/FAIL/EMPTY + 超预算
明细 + 类型化优化建议,每条 `reason` 可解释)。
```python
from perf_budget import PerformanceBudget, BudgetVerifier, ResourceMeasurement, ResourceType
budget = PerformanceBudget.default_cockpit() # 首屏 ≤ 2s
report = BudgetVerifier(budget).verify([
ResourceMeasurement("app.js", ResourceType.JS, 700, block_render=True),
ResourceMeasurement("app.css", ResourceType.CSS, 250, block_render=True),
])
assert report.passed # PASS + 裕量 reason
```
## 2. 图表懒加载策略(`lazy_load.py`)
- `LazyLoadStrategy` —— 4 种加载时机:`immediate`(首屏立即)/`visible`(进视口)/
`idle`(空闲时)/`never`(不加载)。
- `LazyLoadPolicy` —— 策略规则(首屏视口行数、rootMargin 预加载、分页阈值、虚拟滚动)。
- `LazyLoadPlanner` —— 决策器:widget 布局坐标 + 视口/滚动位置 → `LazyLoadPlan`
(每个 widget 的加载决策 + 分页计划 + 虚拟滚动窗口,`reason` 可解释)。
```python
from perf_budget import LazyLoadPlanner, WidgetLayout
plan = LazyLoadPlanner().plan([
WidgetLayout("proc", "process_view", y=0, h=4, always_load=True),
WidgetLayout("trend", "trend", y=10, h=2), # 视口外 → idle
], scroll_y_rows=0)
print(plan.immediate_ids, plan.idle_ids, plan.pages)
```
## 测试
```bash
python -m unittest discover -s templates/ti-cl4/perf-budget/tests -p "test_*.py" -v
```
覆盖正常 + 边界 + 错误(32 用例):预算构造/查询、关键路径串行/并行口径、达标/超预算
场景、always_load 强制加载、视口边界、分页/虚拟滚动、输入校验。