| 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(); | |