File size: 1,340 Bytes
1b21241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const { performance } = require('perf_hooks');

/**
 * 性能监控工具模块
 */
class PerformanceMonitor {
    constructor() {
        this.timers = new Map();
    }

    /**
     * 开始计时
     * @param {string} label - 计时器标签
     */
    start(label) {
        this.timers.set(label, performance.now());
        console.log(`[性能监控] 开始任务: ${label}`);
    }

    /**
     * 结束计时并输出结果
     * @param {string} label - 计时器标签
     */
    end(label) {
        const startTime = this.timers.get(label);
        if (!startTime) {
            console.warn(`[性能监控] 未找到标签为 "${label}" 的计时器`);
            return;
        }
        const endTime = performance.now();
        const duration = (endTime - startTime).toFixed(3);
        console.log(`[性能监控] 结束任务: ${label}, 耗时: ${duration}ms`);
        this.timers.delete(label);
        this.logMemoryUsage();
    }

    /**
     * 输出当前内存使用情况
     */
    logMemoryUsage() {
        const used = process.memoryUsage();
        console.log(`[内存监控] RSS: ${(used.rss / 1024 / 1024).toFixed(2)} MB, Heap Total: ${(used.heapTotal / 1024 / 1024).toFixed(2)} MB, Heap Used: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB`);
    }
}

module.exports = new PerformanceMonitor();