Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - Programmatically get memory usage in Chrome

How can I programmatically get memory usage (JS and total) of my website in Google Chrome?

I looked at doing it from a Chrome extension using the undocumented HeapProfiler (see here), but I can't find a way to get data from that.

I want to measure the memory consumption it at every release, so this needs to be programmatic.

EDIT: I figured out how to get the HeapProfiler method to work. Each addHeapSnapshotChunk event has a chunk of a JSON object.

chrome.browserAction.onClicked.addListener(function(tab) {
  var heapData,
    debugId = {tabId:tab.id};
  chrome.debugger.attach(debugId, '1.0', function() {    
    chrome.debugger.sendCommand(debugId, 'Debugger.enable', {}, function() {
      function headerListener(source, name, data) {
        if(source.tabId == tab.id && name == 'HeapProfiler.addProfileHeader') {
          function chunkListener(source, name, data) {
            if(name == 'HeapProfiler.addHeapSnapshotChunk') {
              heapData += data.chunk;
            } else if(name == 'HeapProfiler.finishHeapSnapshot') {
              chrome.debugger.onEvent.removeListener(chunkListener);
              chrome.debugger.detach(debugId);
              //do something with data
              console.log('Collected ' + heapData.length + ' bytes of JSON data');
            }
          }
          chrome.debugger.onEvent.addListener(chunkListener);
          chrome.debugger.sendCommand(debugId, 'HeapProfiler.getHeapSnapshot', {uid:data.header.uid, type:data.header.typeId});
        }
        chrome.debugger.onEvent.removeListener(headerListener);
      }
      chrome.debugger.onEvent.addListener(headerListener);
      chrome.debugger.sendCommand(debugId, 'HeapProfiler.takeHeapSnapshot');
    });
  });
});

When parsed, the JSON has nodes, edges, and descriptive metadata about the node and edge types and fields.

Alternatively, I could use Timeline events if I just want totals.

That said, are there any better ways than what I've found out here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For anyone that finds this in the future, since version 20 Chrome supports window.performance.memory, which returns something like:

{
  totalJSHeapSize: 21700000,
  usedJSHeapSize: 13400000,
  jsHeapSizeLimit: 1620000000
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...