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) => ` + + ${i+1} + ${escapeHtml(b.opcode)} + ${b.count} + ${fmt(b.selfTime)} + ${pct(b.selfTime, d.duration)} + ${fmt(b.avgTime)} + + `).join('') || '无热点数据'; + + const ts = d.threadStats; + return ` + +
+

性能剖析报告

+
+ 剖析时长: ${fmt(d.duration)} + 采样点: ${d.sampleCount} + 涉及积木类型: ${d.blockCount} +
+
+
+

热点积木 Top ${d.hotBlocks.length}

+ + + ${hotRows} +
排名Opcode调用次数自执行时间占比平均耗时
+
+
+

线程与资源统计

+
+
平均线程数
${ts.avgThreadCount?.toFixed(1) || 0}
+
峰值线程数
${ts.maxThreads || 0}
+
运行态样本占比
${ts.totalRunningSamples ? ((ts.totalRunningSamples/d.sampleCount)*100).toFixed(1)+'%' : '0%'}
+
等待/阻塞态占比
${ts.totalWaitingSamples ? ((ts.totalWaitingSamples/d.sampleCount)*100).toFixed(1)+'%' : '0%'}
+
峰值克隆数
${ts.maxCloneCount || 0}
+
结束时克隆数
${ts.finalCloneCount || 0}
+
列表项增长
${ts.listItemsGrowth || 0}
+
变量增长
${ts.varCountGrowth || 0}
+
+
+
+

建议

+ +
+ `; + } + + function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, c => { + switch (c) { + case '&': return '&'; + case '<': return '<'; + case '>': return '>'; + case '"': return '"'; + case "'": return "'"; + default: return c; + } + }); + } + + // 注册全局 API + window.RWPerformanceProfiler = { + start: startProfiling, + stop: stopProfiling, + isProfiling: () => profiling + }; + + // 工具菜单入口(通过 menu-bar.jsx 绑定全局事件) + addon.settings.addEventListener('change', () => { + profileDuration = addon.settings.get('profileDuration') * 1000; + sampleInterval = addon.settings.get('sampleInterval'); + hotBlockLimit = addon.settings.get('hotBlockLimit'); + }); +} + diff --git a/src/addons/addons/performance-profiler/userstyle.css b/src/addons/addons/performance-profiler/userstyle.css new file mode 100644 index 00000000000..12528fa0b97 --- /dev/null +++ b/src/addons/addons/performance-profiler/userstyle.css @@ -0,0 +1,79 @@ +/* Performance Profiler styles */ +.rw-pp-header { + border-bottom: 1px solid var(--ui-black-transparent); + padding-bottom: 12px; + margin-bottom: 8px; +} +.rw-pp-header h2 { + margin: 0 0 8px; + font-size: 16px; + color: var(--text-primary); +} +.rw-pp-table { + width: 100%; + border-collapse: collapse; + font-size: 12px; + margin-top: 8px; +} +.rw-pp-table th, +.rw-pp-table td { + border: 1px solid var(--ui-black-transparent); + padding: 6px 8px; + text-align: left; + color: var(--text-primary); +} +.rw-pp-table th { + background: var(--ui-secondary); + font-weight: 600; +} +.rw-pp-table tr:nth-child(even) td { + background: var(--ui-black-transparent); +} +.rw-pp-table code { + background: var(--ui-black-transparent); + padding: 1px 4px; + border-radius: 3px; + font-family: var(--code-font, monospace); + font-size: 11px; +} +.rw-pp-section h3 { + margin: 0 0 8px; + font-size: 14px; + color: var(--text-primary); +} +.rw-pp-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: 10px; + margin-top: 8px; +} +.rw-pp-card { + background: var(--ui-modal-background); + border: 1px solid var(--ui-black-transparent); + border-radius: 6px; + padding: 10px 12px; +} +.rw-pp-card .label { + font-size: 11px; + color: var(--text-secondary); + margin-bottom: 3px; +} +.rw-pp-card .value { + font-size: 15px; + font-weight: 600; + color: var(--text-primary); +} +.rw-pp-section ul { + margin: 6px 0 0; + padding-left: 18px; + font-size: 12px; + color: var(--text-secondary); +} +.rw-pp-section li { + margin-bottom: 4px; +} +.rw-pp-section code { + background: var(--ui-black-transparent); + padding: 1px 4px; + border-radius: 3px; +} \ No newline at end of file diff --git a/src/addons/generated/addon-entries.js b/src/addons/generated/addon-entries.js index e0b062ec287..1b76c03be8e 100644 --- a/src/addons/generated/addon-entries.js +++ b/src/addons/generated/addon-entries.js @@ -89,4 +89,5 @@ export default { "calculator": () => import(/* webpackChunkName: "addon-entry-calculator" */ "../addons/calculator/_runtime_entry.js"), "project-size-display": () => import(/* webpackChunkName: "addon-entry-project-size-display" */ "../addons/project-size-display/_runtime_entry.js"), "resize-selected-item": () => import(/* webpackChunkName: "addon-entry-resize-selected-item" */ "../addons/resize-selected-item/_runtime_entry.js"), + "performance-profiler": () => import(/* webpackChunkName: "addon-entry-performance-profiler" */ "../addons/performance-profiler/_runtime_entry.js"), }; \ No newline at end of file diff --git a/src/addons/generated/addon-manifests.js b/src/addons/generated/addon-manifests.js index 9fe420beb7d..281cfd275ad 100644 --- a/src/addons/generated/addon-manifests.js +++ b/src/addons/generated/addon-manifests.js @@ -1,4 +1,5 @@ /* generated by pull.js */ +import _performance_profiler from "../addons/performance-profiler/_manifest_entry.js"; import _dev_inspector from "../addons/dev-inspector/_manifest_entry.js"; import _editor_devtools from "../addons/editor-devtools/_manifest_entry.js"; import _jump_to_def from "../addons/jump-to-def/_manifest_entry.js"; @@ -177,5 +178,6 @@ export default { "todo": _todo, "calculator": _calculator, "project-size-display": _project_size_display, - "resize-selected-item": _resize_selected_item + "resize-selected-item": _resize_selected_item, + "performance-profiler": _performance_profiler, };