Skip to content

Instantly share code, notes, and snippets.

@countzero
Created July 16, 2020 10:09
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 countzero/ffdacb663b58cb4c85ca9696a4a38417 to your computer and use it in GitHub Desktop.
Save countzero/ffdacb663b58cb4c85ca9696a4a38417 to your computer and use it in GitHub Desktop.
Code to test how much memory is available with Node.js
// Source: https://github.com/Data-Wrangling-with-JavaScript/nodejs-memory-test
//
// Small program to test the maximum amount of allocations in multiple blocks.
// This script searches for the largest allocation amount.
//
//
// Allocate a certain size to test if it can be done.
//
function alloc (size) {
const numbers = size / 8;
const arr = []
arr.length = numbers; // Simulate allocation of 'size' bytes.
for (let i = 0; i < numbers; i++) {
arr[i] = i;
}
return arr;
};
//
// Keep allocations referenced so they aren't garbage collected.
//
const allocations = [];
//
// Allocate successively larger sizes, doubling each time until we hit the limit.
//
function allocToMax () {
console.log("Start");
const field = 'heapUsed';
const mu = process.memoryUsage();
console.log(mu);
const gbStart = mu[field] / 1024 / 1024 / 1024;
console.log(`Start ${Math.round(gbStart * 100) / 100} GB`);
let allocationStep = 100 * 1024;
while (true) {
// Allocate memory.
const allocation = alloc(allocationStep);
// Allocate and keep a reference so the allocated memory isn't garbage collected.
allocations.push(allocation);
// Check how much memory is now allocated.
const mu = process.memoryUsage();
const mbNow = mu[field] / 1024 / 1024 / 1024;
console.log(`Allocated since start ${Math.round((mbNow - gbStart) * 100) / 100} GB`);
}
};
allocToMax();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment