Skip to content

Instantly share code, notes, and snippets.

@olegdovger
Created July 23, 2020 23:50
Show Gist options
  • Save olegdovger/1ec7a8cc9901bb8e98cf3a2e0c107075 to your computer and use it in GitHub Desktop.
Save olegdovger/1ec7a8cc9901bb8e98cf3a2e0c107075 to your computer and use it in GitHub Desktop.
How to measure memory usage in real time
const pidusage = require('pidusage')
const secTimeout = process.argv[2] ? parseInt(process.argv[2]): 3
const pid = parseInt(process.argv[3] || process.pid)
console.log('PID:', process.pid)
console.log('Monitoring of PID:', pid)
console.log('Time interval:', secTimeout, 'seconds')
const compute = async () => await pidusage(pid)
const wait = ms => new Promise(resolve => setTimeout(() => resolve(), ms))
const mb = (n = 0) => `${Math.floor(n / (1024 * 1024))}MB`
const percent = (n = 0, all = 1) => `${(100 * n / all).toFixed(1)}%`
const gen = async function *() {
const stat = await compute()
const startMemory = stat.memory
const hrstart = process.hrtime()
while(true) {
const stat = await compute()
const m = stat.memory
const memStr = `mem - ${mb(m)}`
yield memStr
const diff = m - startMemory
let memDiffStr = (diff >= 0) ? `: +${mb(diff)} (+${percent(diff, m)})` : `: ${mb(diff)} (${percent(diff, m)})`
const memStrLen = memStr.length
const memStrDiffLen = memDiffStr.length
const cpuStr = `${stat.cpu.toFixed(1)}`
const cpuStrLen = cpuStr.length
yield memDiffStr
yield ' '.repeat(40 - memStrLen - memStrDiffLen)
yield '| '
yield 'cpu - '
yield cpuStr
yield ' '.repeat(10 - cpuStrLen)
yield '| '
const hrend = process.hrtime(hrstart)
const hours = Math.floor(hrend[0]/3600)
const minutes = Math.floor(hrend[0]/60)%60
const seconds = hrend[0]%60
const milliseconds = (hrend[1] / 1000000).toFixed(3)
const timeSpendStr = `${hours}h ${minutes}m ${seconds}s ${milliseconds}ms`
yield timeSpendStr
yield ' '.repeat(20 - timeSpendStr.length)
yield '| '
const dateStr = new Date().toString()
yield dateStr
yield ' '.repeat(60 - dateStr.length)
yield '| '
yield `\n`
await wait(secTimeout * 1000)
}
}
;(async () => {
const run = gen()
while(true) {
const data = await run.next()
process.stdout.write(data.value)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment