diff --git a/src/addons/addons.js b/src/addons/addons.js index a8d65fa9529..e9f4d0f0856 100644 --- a/src/addons/addons.js +++ b/src/addons/addons.js @@ -12,6 +12,7 @@ const addons = [ 'mediarecorder', 'drag-drop', 'debugger', + 'performance-profiler', 'canvas-screenshot', 'mute-project', 'vol-slider', diff --git a/src/addons/addons/performance-profiler/_manifest_entry.js b/src/addons/addons/performance-profiler/_manifest_entry.js new file mode 100644 index 00000000000..08ae7fefc8d --- /dev/null +++ b/src/addons/addons/performance-profiler/_manifest_entry.js @@ -0,0 +1,53 @@ +/* generated by pull.js */ +const manifest = { + editorOnly: true, + name: '性能剖析报告', + description: '30秒性能剖析:热点积木、内存增长、线程阻塞、克隆统计', + credits: [ + {name: 'RemixWarp', link: ''} + ], + userscripts: [ + {url: 'userscript.js'} + ], + userstyles: [ + {url: 'userstyle.css'} + ], + settings: [ + { + dynamic: true, + name: '剖析时长(秒)', + id: 'profileDuration', + type: 'integer', + min: 5, + max: 300, + default: 30 + }, + { + dynamic: true, + name: '采样间隔(毫秒)', + id: 'sampleInterval', + type: 'integer', + min: 50, + max: 1000, + default: 100 + }, + { + dynamic: true, + name: '热点积木显示上限', + id: 'hotBlockLimit', + type: 'integer', + min: 10, + max: 100, + default: 30 + } + ], + info: [ + { + text: '点击工具菜单 → 性能剖析 启动。完成后自动弹窗展示热点积木、线程阻塞、内存趋势。', + id: 'pp-usage' + } + ], + tags: ['editor', 'analysis', 'remixwarp', 'performance', 'new'], + enabledByDefault: true +}; +export default manifest; \ No newline at end of file diff --git a/src/addons/addons/performance-profiler/_runtime_entry.js b/src/addons/addons/performance-profiler/_runtime_entry.js new file mode 100644 index 00000000000..4904adb2e15 --- /dev/null +++ b/src/addons/addons/performance-profiler/_runtime_entry.js @@ -0,0 +1,8 @@ +/* generated by pull.js */ +import _js from "./userscript.js"; +import _css from "!css-loader!./userstyle.css"; + +export const resources = { + "userscript.js": _js, + "userstyle.css": _css +}; \ No newline at end of file diff --git a/src/addons/addons/performance-profiler/userscript.js b/src/addons/addons/performance-profiler/userscript.js new file mode 100644 index 00000000000..7ea4bfd397e --- /dev/null +++ b/src/addons/addons/performance-profiler/userscript.js @@ -0,0 +1,287 @@ +import WindowManager from '../../window-system/window-manager.js'; + +let Profiler = null; +try { Profiler = require('scratch-vm/src/engine/profiler'); } catch (e) { Profiler = null; } + +const PERFORMANCE_AVAILABLE = typeof window !== 'undefined' && window.performance && window.performance.now; + +export default async function ({ addon, msg, console }) { + if (!PERFORMANCE_AVAILABLE || !Profiler) { + console.warn('Performance profiler unavailable: missing performance.now or profiler'); + return; + } + + const vm = addon.tab.traps.vm; + const runtime = vm.runtime; + + let profileDuration = addon.settings.get('profileDuration') * 1000; + let sampleInterval = addon.settings.get('sampleInterval'); + let hotBlockLimit = addon.settings.get('hotBlockLimit'); + + addon.settings.addEventListener('change', () => { + profileDuration = addon.settings.get('profileDuration') * 1000; + sampleInterval = addon.settings.get('sampleInterval'); + hotBlockLimit = addon.settings.get('hotBlockLimit'); + }); + + let profiling = false; + let profileStartTime = 0; + let frameCallback = null; + let profileTimer = null; + let sampleTimer = null; + + // 采样数据 + const blockCounters = new Map(); // opcode -> {count, selfTime, totalTime} + const threadSamples = []; // [{time, threadCount, runningThreads, waitingThreads, cloneCount, listItems, varCount}] + let profilingActive = false; + + function getOpcodeName(id) { + try { return runtime.profiler ? runtime.profiler.nameById(id) : null; } catch { return null; } + } + + function onProfilerFrame(frame) { + if (!profilingActive) return; + if (frame.id < 0) return; + const name = getOpcodeName(frame.id); + if (!name) return; + if (!name.startsWith('blockFunction') && frame.arg) { + const opcode = frame.arg; + if (!blockCounters.has(opcode)) blockCounters.set(opcode, {count: 0, selfTime: 0, totalTime: 0}); + const entry = blockCounters.get(opcode); + entry.count += frame.count || 1; + entry.selfTime += frame.selfTime || 0; + entry.totalTime += frame.totalTime || 0; + } + } + + function sampleThreads() { + if (!profilingActive) return; + const threads = runtime.threads; + let running = 0, waiting = 0, blocked = 0; + for (const t of threads) { + if (t.updateMonitor) continue; + if (t.status === 0) running++; + else if (t.status === 1 || t.status === 2 || t.status === 3) waiting++; + else blocked++; + } + threadSamples.push({ + time: performance.now() - profileStartTime, + totalThreads: threads.length, + running, + waiting, + blocked, + cloneCount: runtime._cloneCounter, + listItems: countListItems(), + varCount: countVariables() + }); + } + + function countVariables() { + let count = 0; + for (const target of runtime.targets) { + if (!target.isOriginal) continue; + for (const id in target.variables) { + if (target.variables[id].type === '') count++; + } + } + return count; + } + + function countListItems() { + let count = 0; + for (const target of runtime.targets) { + for (const id in target.variables) { + const v = target.variables[id]; + if (v.type === 'list' && Array.isArray(v.value)) count += v.value.length; + } + } + return count; + } + + function startProfiling() { + if (profiling) return; + profiling = true; + profilingActive = true; + blockCounters.clear(); + threadSamples.length = 0; + profileStartTime = performance.now(); + + if (runtime.enableProfiling) { + frameCallback = (frame) => { + if (!profilingActive) return; + if (frame.id < 0) return; + const opcode = frame.arg; + if (opcode && typeof opcode === 'string' && !name.startsWith('Runtime') && !name.startsWith('Sequencer')) { + if (!blockCounters.has(opcode)) blockCounters.set(opcode, {count: 0, selfTime: 0, totalTime: 0}); + const entry = blockCounters.get(opcode); + entry.count += frame.count || 1; + entry.selfTime += frame.selfTime || 0; + entry.totalTime += frame.totalTime || 0; + } + }; + runtime.enableProfiling(frameCallback); + } + + sampleTimer = setInterval(sampleThreads, sampleInterval); + profileTimer = setTimeout(stopProfiling, profileDuration); + } + + function stopProfiling() { + if (!profiling) return; + profiling = false; + profilingActive = false; + if (profileTimer) clearTimeout(profileTimer); + if (sampleTimer) clearInterval(sampleTimer); + if (runtime.disableProfiling) runtime.disableProfiling(); + frameCallback = null; + + // 等待最后一次 profiler 报告 + setTimeout(() => generateReport(), 100); + } + + function generateReport() { + const duration = performance.now() - profileStartTime; + const hotBlocks = Array.from(blockCounters.entries()) + .map(([opcode, data]) => ({opcode, ...data, avgTime: data.count ? data.selfTime / data.count : 0})) + .sort((a, b) => b.selfTime - a.selfTime) + .slice(0, hotBlockLimit); + + const threadStats = threadSamples.length ? { + avgThreadCount: threadSamples.reduce((s, t) => s + t.totalThreads, 0) / threadSamples.length, + maxThreads: Math.max(...threadSamples.map(t => t.totalThreads)), + totalRunningSamples: threadSamples.reduce((s, t) => s + t.running, 0), + totalWaitingSamples: threadSamples.reduce((s, t) => s + t.waiting, 0), + maxCloneCount: Math.max(...threadSamples.map(t => t.cloneCount)), + finalCloneCount: threadSamples[threadSamples.length - 1]?.cloneCount || 0, + listItemsGrowth: threadSamples.length > 1 ? threadSamples[threadSamples.length - 1].listItems - threadSamples[0].listItems : 0, + varCountGrowth: threadSamples.length > 1 ? threadSamples[threadSamples.length - 1].varCount - threadSamples[0].varCount : 0 + } : {}; + + showReportWindow({ + duration, + blockCount: blockCounters.size, + hotBlocks, + threadStats, + sampleCount: threadSamples.length + }); + } + + function showReportWindow(data) { + const win = WindowManager.createWindow({ + id: 'rw-performance-profiler-report', + title: '性能剖析报告', + width: 700, + height: 520, + onClose: () => {} + }); + + const content = win.getContentElement(); + content.style.padding = '16px'; + content.style.fontSize = '13px'; + content.style.lineHeight = '1.5'; + content.innerHTML = buildReportHTML(data); + win.show(); + } + + function buildReportHTML(d) { + const fmt = (ms) => (ms < 1000 ? `${ms.toFixed(2)}ms` : `${(ms/1000).toFixed(2)}s`); + const pct = (v, total) => total ? ((v/total)*100).toFixed(1) + '%' : '0%'; + const hotRows = d.hotBlocks.map((b, i) => ` +
${escapeHtml(b.opcode)}| 排名 | Opcode | 调用次数 | 自执行时间 | 占比 | 平均耗时 |
|---|
${escapeHtml(d.hotBlocks[0].opcode)} 占用 ${((d.hotBlocks[0].selfTime/d.duration)*100).toFixed(1)}% CPU 时间,考虑优化或拆分脚本