Created
November 4, 2020 18:25
-
-
Save abhi5658/86516745f3e70d2a5f356433bab6d46f to your computer and use it in GitHub Desktop.
The setup helps to monitor memory used by node process to execute a function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const myFunction = async (args) => { | |
// do something in this function whose memory you want to monitor | |
return 0; | |
} | |
function sleep(ms) { | |
return new Promise((resolve) => { | |
console.log(`***\n***\nsleeping for ${ms / 1000} seconds`) | |
setTimeout(resolve, ms); | |
}); | |
} | |
const mem = (val) => `${Math.round((val / 1024) * 100) / 100} KB`; | |
const memoryUsage = () => { | |
return setInterval(() => { | |
const u = process.memoryUsage(); | |
console.log( | |
'rss', mem(u.rss), | |
// '\ttotal', mem(u.heapTotal), | |
'\tused', mem(u.heapUsed), | |
'\text', mem(u.external), | |
// '\tarr', mem(u.arrayBuffers) | |
); | |
}, 2000); | |
} | |
const processApp = async () => { | |
try { | |
// start buffer time to see initial memory usage | |
await sleep(5000); | |
console.time('process') | |
console.log('started process'); | |
// memory consuming function called here | |
const data = await myFunction(args); | |
console.log('after function finished'); | |
// end buffer time to watch memory usage | |
await sleep(30000); | |
console.log('end process'); | |
console.timeEnd('process') | |
} catch (error) { | |
console.log('process error', error); | |
} | |
} | |
const runApp = async () => { | |
const logMem = memoryUsage(); | |
await processApp(); | |
clearInterval(logMem); | |
} | |
runApp(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment