Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | /** * 性能分析器 * * @description 用于测量和分析渲染引擎各个阶段的性能 * * 功能: * 1. 测量操作执行时间 * 2. 统计多次调用的平均/最大/最小时间 * 3. 生成性能报告 * 4. 标记关键性能指标 */ // ==================== 类型定义 ==================== /** 单个操作的性能统计 */ export interface OperationStats { /** 操作名称 */ name: string; /** 调用次数 */ count: number; /** 总耗时(毫秒) */ totalTime: number; /** 平均耗时(毫秒) */ avgTime: number; /** 最小耗时(毫秒) */ minTime: number; /** 最大耗时(毫秒) */ maxTime: number; /** 最后一次耗时(毫秒) */ lastTime: number; } /** 性能报告 */ export interface PerformanceReport { [operationName: string]: OperationStats; } /** 性能标记 */ export interface PerformanceMark { /** 标记名称 */ name: string; /** 开始时间 */ startTime: number; /** 结束时间 */ endTime?: number; } /** 分析器配置 */ export interface ProfilerConfig { /** 是否启用分析器 */ enabled: boolean; /** 是否自动打印日志 */ autoLog: boolean; /** 警告阈值(毫秒),超过此值会打印警告 */ warningThreshold: number; } // ==================== 默认配置 ==================== const DEFAULT_CONFIG: ProfilerConfig = { enabled: true, autoLog: false, warningThreshold: 100, }; // ==================== 主类 ==================== /** * 性能分析器 */ export class PerformanceProfiler { /** 配置 */ private config: ProfilerConfig; /** 操作统计 */ private stats: Map<string, OperationStats> = new Map(); /** 当前运行中的标记 */ private activeMarks: Map<string, PerformanceMark> = new Map(); /** 性能指标历史 */ private history: Array<{ timestamp: number; operation: string; duration: number }> = []; /** 最大历史记录数 */ private maxHistorySize: number = 1000; /** * 构造函数 * @param config 配置选项 */ constructor(config: Partial<ProfilerConfig> = {}) { this.config = { ...DEFAULT_CONFIG, ...config }; } /** * 开始计时 * @param operationName 操作名称 */ start(operationName: string): void { if (!this.config.enabled) return; this.activeMarks.set(operationName, { name: operationName, startTime: performance.now(), }); } /** * 结束计时 * @param operationName 操作名称 * @returns 本次操作耗时(毫秒) */ end(operationName: string): number { if (!this.config.enabled) return 0; const endTime = performance.now(); const mark = this.activeMarks.get(operationName); if (!mark) { console.warn(`[PerformanceProfiler] 未找到操作 "${operationName}" 的开始标记`); return 0; } const duration = endTime - mark.startTime; this.activeMarks.delete(operationName); // 更新统计 this.updateStats(operationName, duration); // 添加到历史记录 this.addHistory(operationName, duration); // 自动打印日志 if (this.config.autoLog) { console.log(`[Performance] ${operationName}: ${duration.toFixed(2)}ms`); } // 警告检查 if (duration > this.config.warningThreshold) { console.warn(`[Performance Warning] ${operationName} 耗时 ${duration.toFixed(2)}ms 超过阈值 ${this.config.warningThreshold}ms`); } return duration; } /** * 包装函数并计时 * @param operationName 操作名称 * @param fn 要执行的函数 * @returns 函数执行结果 */ measure<T>(operationName: string, fn: () => T): T { this.start(operationName); try { const result = fn(); return result; } finally { this.end(operationName); } } /** * 包装异步函数并计时 * @param operationName 操作名称 * @param fn 要执行的异步函数 * @returns Promise */ async measureAsync<T>(operationName: string, fn: () => Promise<T>): Promise<T> { this.start(operationName); try { const result = await fn(); return result; } finally { this.end(operationName); } } /** * 更新操作统计 * @param operationName 操作名称 * @param duration 本次耗时 */ private updateStats(operationName: string, duration: number): void { const existing = this.stats.get(operationName); if (existing) { existing.count++; existing.totalTime += duration; existing.avgTime = existing.totalTime / existing.count; existing.minTime = Math.min(existing.minTime, duration); existing.maxTime = Math.max(existing.maxTime, duration); existing.lastTime = duration; } else { this.stats.set(operationName, { name: operationName, count: 1, totalTime: duration, avgTime: duration, minTime: duration, maxTime: duration, lastTime: duration, }); } } /** * 添加历史记录 * @param operationName 操作名称 * @param duration 耗时 */ private addHistory(operationName: string, duration: number): void { this.history.push({ timestamp: Date.now(), operation: operationName, duration, }); // 限制历史记录大小 if (this.history.length > this.maxHistorySize) { this.history.shift(); } } /** * 获取性能报告 * @returns 性能报告对象 */ getReport(): PerformanceReport { const report: PerformanceReport = {}; for (const [name, stats] of this.stats) { report[name] = { ...stats }; } return report; } /** * 获取单个操作的统计 * @param operationName 操作名称 * @returns 操作统计,如果不存在则返回undefined */ getStats(operationName: string): OperationStats | undefined { const stats = this.stats.get(operationName); return stats ? { ...stats } : undefined; } /** * 获取历史记录 * @param limit 限制数量 * @returns 历史记录数组 */ getHistory(limit?: number): Array<{ timestamp: number; operation: string; duration: number }> { if (limit) { return this.history.slice(-limit); } return [...this.history]; } /** * 打印性能报告到控制台 */ printReport(): void { console.group('📊 性能分析报告'); const report = this.getReport(); const entries = Object.entries(report).sort((a, b) => b[1].totalTime - a[1].totalTime); console.table(entries.map(([_, stats]) => ({ 操作: stats.name, 次数: stats.count, 总耗时: `${stats.totalTime.toFixed(2)}ms`, 平均: `${stats.avgTime.toFixed(2)}ms`, 最小: `${stats.minTime.toFixed(2)}ms`, 最大: `${stats.maxTime.toFixed(2)}ms`, }))); console.groupEnd(); } /** * 重置所有统计 */ reset(): void { this.stats.clear(); this.activeMarks.clear(); this.history = []; } /** * 重置指定操作的统计 * @param operationName 操作名称 */ resetOperation(operationName: string): void { this.stats.delete(operationName); this.activeMarks.delete(operationName); } /** * 获取当前配置 */ getConfig(): ProfilerConfig { return { ...this.config }; } /** * 更新配置 * @param config 新配置 */ updateConfig(config: Partial<ProfilerConfig>): void { Object.assign(this.config, config); } /** * 启用分析器 */ enable(): void { this.config.enabled = true; } /** * 禁用分析器 */ disable(): void { this.config.enabled = false; } /** * 检查是否启用 */ isEnabled(): boolean { return this.config.enabled; } } // ==================== 工厂函数 ==================== /** * 创建性能分析器实例 * @param config 配置选项 * @returns PerformanceProfiler实例 */ export function createPerformanceProfiler(config?: Partial<ProfilerConfig>): PerformanceProfiler { return new PerformanceProfiler(config); } // ==================== 全局实例 ==================== /** 全局性能分析器实例 */ let globalProfiler: PerformanceProfiler | null = null; /** * 获取全局性能分析器实例 * @returns 全局PerformanceProfiler实例 */ export function getGlobalProfiler(): PerformanceProfiler { if (!globalProfiler) { globalProfiler = new PerformanceProfiler(); } return globalProfiler; } /** * 重置全局性能分析器 */ export function resetGlobalProfiler(): void { if (globalProfiler) { globalProfiler.reset(); } } // ==================== 便捷函数 ==================== /** * 快速测量函数执行时间 * @param operationName 操作名称 * @param fn 要执行的函数 * @returns 函数执行结果 */ export function measureTime<T>(operationName: string, fn: () => T): T { return getGlobalProfiler().measure(operationName, fn); } /** * 快速测量异步函数执行时间 * @param operationName 操作名称 * @param fn 要执行的异步函数 * @returns Promise */ export async function measureTimeAsync<T>(operationName: string, fn: () => Promise<T>): Promise<T> { return getGlobalProfiler().measureAsync(operationName, fn); } /** * 格式化耗时 * @param ms 毫秒数 * @returns 格式化后的字符串 */ export function formatDuration(ms: number): string { if (ms < 1) { return `${(ms * 1000).toFixed(0)}μs`; } else if (ms < 1000) { return `${ms.toFixed(2)}ms`; } else { return `${(ms / 1000).toFixed(2)}s`; } } |