| 33 | } |
| 34 | |
| 35 | function analyzeProfile(profilePath: string): void { |
| 36 | // Read and parse the profile file |
| 37 | const profileData = readFileSync(profilePath, 'utf8') |
| 38 | const profile: CPUProfile = JSON.parse(profileData) |
| 39 | |
| 40 | console.log(`Analyzing profile: ${profilePath}\n`) |
| 41 | |
| 42 | // Aggregate time by function name |
| 43 | const timeByFunction = new Map<string, FunctionStats>() |
| 44 | |
| 45 | profile.nodes.forEach(node => { |
| 46 | const funcName = node.callFrame.functionName || '(anonymous)' |
| 47 | const url = node.callFrame.url |
| 48 | const fileName = url.split('/').pop() || '' |
| 49 | const key = `${funcName} [${fileName}:${node.callFrame.lineNumber}]` |
| 50 | |
| 51 | if (!timeByFunction.has(key)) { |
| 52 | timeByFunction.set(key, {hitCount: 0, url}) |
| 53 | } |
| 54 | |
| 55 | const data = timeByFunction.get(key)! |
| 56 | data.hitCount += node.hitCount || 0 |
| 57 | }) |
| 58 | |
| 59 | // Sort by hit count |
| 60 | const sorted: FunctionEntry[] = Array.from(timeByFunction.entries()) |
| 61 | .map(([name, data]) => ({name, ...data})) |
| 62 | .filter(item => item.hitCount > 0 && !item.url.includes('node:internal')) |
| 63 | .sort((a, b) => b.hitCount - a.hitCount) |
| 64 | .slice(0, 40) |
| 65 | |
| 66 | console.log('Top 40 functions by CPU time (hit count):') |
| 67 | console.log('==========================================\n') |
| 68 | sorted.forEach((item, i) => { |
| 69 | console.log(`${i + 1}. ${item.name}`) |
| 70 | console.log(` Hit count: ${item.hitCount}`) |
| 71 | console.log(` File: ${item.url}`) |
| 72 | console.log('') |
| 73 | }) |
| 74 | |
| 75 | // Also group by file |
| 76 | const timeByFile = new Map<string, number>() |
| 77 | profile.nodes.forEach(node => { |
| 78 | const url = node.callFrame.url |
| 79 | if (url.includes('node:internal') || !url.includes('formatjs')) return |
| 80 | |
| 81 | const fileName = url.split('/packages/').pop() |
| 82 | if (!fileName) return |
| 83 | |
| 84 | if (!timeByFile.has(fileName)) { |
| 85 | timeByFile.set(fileName, 0) |
| 86 | } |
| 87 | |
| 88 | timeByFile.set(fileName, timeByFile.get(fileName)! + (node.hitCount || 0)) |
| 89 | }) |
| 90 | |
| 91 | const sortedByFile: FileEntry[] = Array.from(timeByFile.entries()) |
| 92 | .map(([name, hitCount]) => ({name, hitCount})) |