Skip to content

Instantly share code, notes, and snippets.

@CarsonMcKinstry
Created November 19, 2019 13:55
Show Gist options
  • Select an option

  • Save CarsonMcKinstry/b5b96d64d99675020dc41480a16e69de to your computer and use it in GitHub Desktop.

Select an option

Save CarsonMcKinstry/b5b96d64d99675020dc41480a16e69de to your computer and use it in GitHub Desktop.
import * as fs from "fs";
export function memoryUsageLog(
file: string | Writable,
sampleRate: number = 1,
sampleTime: number = 60,
debug: boolean = false,
callback = () => {}
) {
const output = typeof file === "string" ? fs.createWriteStream(file) : file;
output.write("time, rss, head\n");
let rowCount = 0;
setTimeout(() => {
console.log("Sampling done");
callback();
process.exit(0);
}, sampleTime * 1000);
console.log("Sampling start with the following settings:");
console.log(
`Sampling time: ${Math.floor(sampleTime / 60)}m${sampleTime % 60}s`
);
console.log(`Sample Rate: ${sampleRate} per second`);
console.log(`Log written to: ${file}`);
setInterval(() => {
rowCount++;
var mem = process.memoryUsage();
var fmt = (v: number) => (v / (1024 * 1024)).toFixed(0) + "MB";
output.write(`${rowCount},${mem.rss}, ${mem.heapUsed}\n`);
if (debug) {
console.log("RSS = " + fmt(mem.rss), "Heap = " + fmt(mem.heapUsed));
}
}, Math.floor(1000 / sampleRate));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment