Skip to content

Instantly share code, notes, and snippets.

@aalexand
Last active April 25, 2018 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalexand/07c8e6eef3040f49b68a570e8c90daa6 to your computer and use it in GitHub Desktop.
Save aalexand/07c8e6eef3040f49b68a570e8c90daa6 to your computer and use it in GitHub Desktop.
const heapProfile = require('heap-profile');
heapProfile.start({sampleIntervalBytes: 32 * 1024, stackDepth: 128});
function totalHeapSize(n) {
let size = 0;
for (let a of n.allocations) {
size += a.size * a.count;
}
for (let ch of n.children) {
size += totalHeapSize(ch);
}
return size;
}
let rss = 0;
let heapTotal = 0;
let heapUsed = 0;
let heapUsedProfiler = 0;
let numProfiles = 0;
setInterval(() => {
let mu = process.memoryUsage();
rss = mu.rss;
heapTotal = mu.heapTotal;
heapUsed = mu.heapUsed;
heapUsedProfiler = totalHeapSize(heapProfile.get());
numProfiles++;
}, 10);
setInterval(() => {
console.log(
'rss',
(rss / (1024 * 1024)).toFixed(3),
'MiB,',
'heap total',
(heapTotal / (1024 * 1024)).toFixed(3),
'MiB,',
'heap used',
(heapUsed / (1024 * 1024)).toFixed(3),
'MiB,',
'heap used (profiler)',
(heapUsedProfiler / (1024 * 1024)).toFixed(3),
'MiB,',
'profile count',
numProfiles,
);
}, 2000);
// Make 2**depth allocations of size bytes each, at different stacks.
// Returns the array of made allocations.
function allocate(size, depth) {
if (depth == 0) {
return [new Int8Array(size)];
}
return allocate(size, depth-1).concat(allocate2(size, depth-1));
}
function allocate2(size, depth) {
if (depth == 0) {
return [new Int8Array(size)];
}
return allocate(size, depth-1).concat(allocate2(size, depth-1));
}
// Intentionally global to prevent GC.
let ref = [];
let mode = process.argv[2];
if (mode === 'loopalloc') {
setInterval(() => {
if (ref.length > 16) {
ref[15] = null;
ref.shift();
}
ref.push(allocate(128, 16)); // 128 bytes * 2**16 = 2**23 bytes = 8 MiB
}, 1000);
} else if (mode === 'expressapp') {
const express = require('express')
const app = express()
const http = require('http');
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(3000, () => {
console.log('Express app listening on port 3000...');
// Simulate some server load.
setInterval(() => {
http.get('http://localhost:3000/', (resp) => {
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}, 1);
});
} else {
throw new Error('Expected "loopalloc" or "expressapp", got "' + mode + '"');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment