javascriptmemorymemory-managementgoogle-chrome-devtoolspuppeteer

How to Get Total Memory Usage of a Chrome Tab


I am trying to obtain the total memory usage (similar to what is shown in Chrome's Task Manager as "Memory Footprint") of a Chrome tab. While I can get the JavaScript heap size using performance.memory, I need a more comprehensive measure that includes the total memory usage of the tab. Memory Footprint example

Here is the code I am using:

(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`);
})();

Issues: The script retrieves JavaScript heap size metrics, but this is not enough to get the total memory footprint of the tab.


Solution

  • This code snippet demonstrates how to use Puppeteer to gather memory usage information for each process associated with a Chromium browser instance:

    import puppeteer from "puppeteer";
    import { exec } from "child_process";
    import { promisify } from "util";
    
    const browser = await puppeteer.launch({ headless: "new" });
    const client = await browser.target().createCDPSession();
    const { processInfo } = await client.send("SystemInfo.getProcessInfo");
    client.detach();
    
    for (const process of processInfo) {
        const { stdout } = await promisify(exec)(`ps -o rss= -p ${process.id}`);
        process.memoryKb = stdout.trim();
    }
    
    await browser.close();
    
    console.log("Process info:", processInfo);
    

    result:

    Process info: [
      { type: 'browser', id: 11159, cpuTime: 0.13, memoryKb: '141900' },
      { type: 'renderer', id: 11229, cpuTime: 0, memoryKb: '54196' },
      { type: 'renderer', id: 11230, cpuTime: 0.01, memoryKb: '79408' },
      { type: 'GPU', id: 11190, cpuTime: 0.03, memoryKb: '95092' },
      { type: 'storage.mojom.StorageService', id: 11193, cpuTime: 0, memoryKb: '40860' }
    ]