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
| // Node.js性能分析
import { performance, PerformanceObserver } from 'perf_hooks';
import v8 from 'v8';
class PerformanceProfiler {
private measurements = new Map<string, number[]>();
// 测量函数执行时间
async measure<T>(
name: string,
fn: () => Promise<T>
): Promise<T> {
const start = performance.now();
const heapBefore = v8.getHeapStatistics().used_heap_size;
try {
const result = await fn();
const duration = performance.now() - start;
const heapAfter = v8.getHeapStatistics().used_heap_size;
const heapDelta = heapAfter - heapBefore;
this.record(name, {
duration,
heapDelta,
timestamp: Date.now()
});
return result;
} catch (error) {
const duration = performance.now() - start;
this.record(name, {
duration,
error: true,
timestamp: Date.now()
});
throw error;
}
}
private record(name: string, metrics: any): void {
if (!this.measurements.has(name)) {
this.measurements.set(name, []);
}
this.measurements.get(name)!.push(metrics);
}
// 获取性能统计
getStats(name: string): PerformanceStats {
const measurements = this.measurements.get(name) || [];
const durations = measurements.map(m => m.duration);
const errors = measurements.filter(m => m.error).length;
return {
count: measurements.length,
avgDuration: this.average(durations),
minDuration: Math.min(...durations),
maxDuration: Math.max(...durations),
p95: this.percentile(durations, 95),
p99: this.percentile(durations, 99),
errorRate: errors / measurements.length
};
}
private average(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0) / numbers.length;
}
private percentile(numbers: number[], p: number): number {
const sorted = numbers.sort((a, b) => a - b);
const index = Math.ceil((p / 100) * sorted.length) - 1;
return sorted[index];
}
}
// 使用示例
const profiler = new PerformanceProfiler();
app.get('/api/users/:id', async (request, response) => {
const user = await profiler.measure('db.getUser', () =>
db.getUser(request.params.id)
);
const posts = await profiler.measure('db.getUserPosts', () =>
db.getUserPosts(request.params.id)
);
response.json({ user, posts });
});
// 定期输出统计
setInterval(() => {
console.log('Performance Stats:');
console.log('getUser:', profiler.getStats('db.getUser'));
console.log('getUserPosts:', profiler.getStats('db.getUserPosts'));
}, 60000);
|