我正在尝试获取 Chrome 选项卡的总内存使用量(类似于 Chrome 任务管理器中显示的“内存占用量”)。虽然我可以使用 Performance.memory 获取 JavaScript 堆大小,但我需要更全面的测量,其中包括选项卡的总内存使用情况。 内存占用示例
这是我正在使用的代码:
(async function getMemoryFootprint() {
const puppeteer = require("puppeteer");
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://www.youtube.com/');
const client = await page.target().createCDPSession();
await client.send("HeapProfiler.enable");
await client.send("HeapProfiler.collectGarbage");
await client.send("HeapProfiler.collectGarbage");
await client.send("HeapProfiler.disable");
const memoryMetrics = await page.metrics();
await browser.close();
console.log(`Total JS Heap Size: ${memoryMetrics.JSHeapTotalSize} bytes`);
console.log(`Used JS Heap Size: ${memoryMetrics.JSHeapUsedSize} bytes`);
})();
问题:脚本检索 JavaScript 堆大小指标,但这不足以获取选项卡的总内存占用量。
我当前的解决方案是使用一个脚本来计算 Chrome 进程的总内存消耗,我从 Node.js 进程调用该脚本:
#!/bin/bash
total_mb=0
while read -r pid rss; do
total_mb=$((total_mb + rss / 1024))
done < <(ps -o pid,rss -C chrome --no-headers)
echo "Total memory usage by Chrome processes: $total_mb MB"