// 内存监控工具 const MemoryMonitor = (() => { let monitorInterval = null; let isMonitoring = false; const formatBytes = (bytes) => { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]; }; const getMemoryInfo = () => { if (performance.memory) { return { used: performance.memory.usedJSHeapSize, total: performance.memory.totalJSHeapSize, limit: performance.memory.jsHeapSizeLimit, usedFormatted: formatBytes(performance.memory.usedJSHeapSize), totalFormatted: formatBytes(performance.memory.totalJSHeapSize), limitFormatted: formatBytes(performance.memory.jsHeapSizeLimit), percentage: ((performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100).toFixed(2) }; } return null; }; const start = (interval = 5000) => { if (isMonitoring) return; isMonitoring = true; console.log('[内存监控] 开始监控,间隔:', interval, 'ms'); monitorInterval = setInterval(() => { const info = getMemoryInfo(); if (info) { console.log(`[内存监控] 使用: ${info.usedFormatted} / ${info.limitFormatted} (${info.percentage}%)`); // 如果内存使用超过70%,发出警告 if (parseFloat(info.percentage) > 70) { console.warn('[内存警告] 内存使用率超过70%,建议清理资源'); } } }, interval); }; const stop = () => { if (monitorInterval) { clearInterval(monitorInterval); monitorInterval = null; isMonitoring = false; console.log('[内存监控] 已停止'); } }; const logCurrent = () => { const info = getMemoryInfo(); if (info) { console.log('[内存状态]', info); } else { console.log('[内存状态] 浏览器不支持 performance.memory API'); } }; return { start, stop, getMemoryInfo, logCurrent }; })(); // 开发环境下自动启动监控 if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') { // 延迟启动,避免影响页面加载 setTimeout(() => { MemoryMonitor.start(10000); // 每10秒监控一次 }, 3000); } window.MemoryMonitor = MemoryMonitor;