-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformanceBenchmark.ts
More file actions
224 lines (185 loc) · 5.55 KB
/
performanceBenchmark.ts
File metadata and controls
224 lines (185 loc) · 5.55 KB
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
/**
* Performance benchmarking utilities for monitoring component render times,
* virtual list performance, and memory usage
*/
export interface PerformanceMetrics {
componentName: string
renderTime: number
timestamp: number
}
export interface MemoryMetrics {
usedJSHeapSize: number
totalJSHeapSize: number
jsHeapSizeLimit: number
}
class PerformanceBenchmark {
private metrics: PerformanceMetrics[] = []
private renderStartTimes: Map<string, number> = new Map()
/**
* Start measuring render time for a component
*/
startRender(componentName: string): void {
this.renderStartTimes.set(componentName, performance.now())
}
/**
* End measuring render time and record metrics
*/
endRender(componentName: string): number {
const startTime = this.renderStartTimes.get(componentName)
if (!startTime) {
console.warn(`No start time found for component: ${componentName}`)
return 0
}
const renderTime = performance.now() - startTime
this.renderStartTimes.delete(componentName)
const metric: PerformanceMetrics = {
componentName,
renderTime,
timestamp: Date.now(),
}
this.metrics.push(metric)
// Keep only last 100 measurements to prevent memory leaks
if (this.metrics.length > 100) {
this.metrics.shift()
}
return renderTime
}
/**
* Measure a function execution time
*/
async measureAsync<T>(
name: string,
fn: () => Promise<T>
): Promise<{ result: T; duration: number }> {
const start = performance.now()
const result = await fn()
const duration = performance.now() - start
console.log(`[Performance] ${name}: ${duration.toFixed(2)}ms`)
return { result, duration }
}
/**
* Measure a synchronous function execution time
*/
measure<T>(name: string, fn: () => T): { result: T; duration: number } {
const start = performance.now()
const result = fn()
const duration = performance.now() - start
console.log(`[Performance] ${name}: ${duration.toFixed(2)}ms`)
return { result, duration }
}
/**
* Get average render time for a component
*/
getAverageRenderTime(componentName: string): number {
const componentMetrics = this.metrics.filter(
m => m.componentName === componentName
)
if (componentMetrics.length === 0) return 0
const total = componentMetrics.reduce((sum, m) => sum + m.renderTime, 0)
return total / componentMetrics.length
}
/**
* Get all metrics for a component
*/
getMetrics(componentName: string): PerformanceMetrics[] {
return this.metrics.filter(m => m.componentName === componentName)
}
/**
* Get all recorded metrics
*/
getAllMetrics(): PerformanceMetrics[] {
return [...this.metrics]
}
/**
* Clear all metrics
*/
clear(): void {
this.metrics = []
this.renderStartTimes.clear()
}
/**
* Get current memory usage (Chrome only)
*/
getMemoryUsage(): MemoryMetrics | null {
if ('memory' in performance && performance.memory) {
const memory = performance.memory as {
usedJSHeapSize: number
totalJSHeapSize: number
jsHeapSizeLimit: number
}
return {
usedJSHeapSize: memory.usedJSHeapSize,
totalJSHeapSize: memory.totalJSHeapSize,
jsHeapSizeLimit: memory.jsHeapSizeLimit,
}
}
return null
}
/**
* Format memory size to human-readable string
*/
formatMemorySize(bytes: number): string {
const mb = bytes / (1024 * 1024)
return `${mb.toFixed(2)} MB`
}
/**
* Log performance summary
*/
logSummary(): void {
const componentNames = new Set(this.metrics.map(m => m.componentName))
console.log('=== Performance Summary ===')
componentNames.forEach(name => {
const avg = this.getAverageRenderTime(name)
const metrics = this.getMetrics(name)
const min = Math.min(...metrics.map(m => m.renderTime))
const max = Math.max(...metrics.map(m => m.renderTime))
console.log(`${name}:`)
console.log(` Renders: ${metrics.length}`)
console.log(` Average: ${avg.toFixed(2)}ms`)
console.log(` Min: ${min.toFixed(2)}ms`)
console.log(` Max: ${max.toFixed(2)}ms`)
})
const memory = this.getMemoryUsage()
if (memory) {
console.log('\nMemory Usage:')
console.log(` Used: ${this.formatMemorySize(memory.usedJSHeapSize)}`)
console.log(` Total: ${this.formatMemorySize(memory.totalJSHeapSize)}`)
console.log(` Limit: ${this.formatMemorySize(memory.jsHeapSizeLimit)}`)
}
console.log('==========================')
}
/**
* Monitor FPS (frames per second)
*/
monitorFPS(callback: (fps: number) => void, duration = 5000): () => void {
let frameCount = 0
let lastTime = performance.now()
let rafId: number
const countFrame = () => {
frameCount++
const currentTime = performance.now()
const elapsed = currentTime - lastTime
if (elapsed >= 1000) {
const fps = Math.round((frameCount * 1000) / elapsed)
callback(fps)
frameCount = 0
lastTime = currentTime
}
rafId = requestAnimationFrame(countFrame)
}
rafId = requestAnimationFrame(countFrame)
// Auto-stop after duration
const timeoutId = setTimeout(() => {
cancelAnimationFrame(rafId)
}, duration)
// Return cleanup function
return () => {
cancelAnimationFrame(rafId)
clearTimeout(timeoutId)
}
}
}
// Export singleton instance
export const performanceBenchmark = new PerformanceBenchmark()
// Export class for testing
export { PerformanceBenchmark }