Skip to content

Instantly share code, notes, and snippets.

@andyvanee
Last active August 19, 2021 19:10
Show Gist options
  • Save andyvanee/7a921daf0d63a87c8f6864c75cfb6921 to your computer and use it in GitHub Desktop.
Save andyvanee/7a921daf0d63a87c8f6864c75cfb6921 to your computer and use it in GitHub Desktop.
Basic profiler for your node scripts

Basic profiler for your node scripts

Usage
import "./profile.js"

// do some stuff...
const items = [...new Array(100)].map((x, i) => i)
for (let i of items) {
    setTimeout(() => console.log(`item ${i}`), 150)
}
Output
$ node run.js
[...]
item 98
item 99

mem(total): 21.36MB	mem(init): 20.71MB	mem(alloc): 0.65MB
time: 164.065ms
samples: 3 interval: 100
Notes

By default, the script will sample every 100ms. You can change this with an environment variable:

$ PROFILE_INTERVAL=20 node run.js
[...]
item 98
item 99

mem(total): 21.35MB	mem(init): 20.66MB	mem(alloc): 0.70MB
time: 167.898ms
samples: 9 interval: 20
console.time("time")
const PROFILE_INTERVAL = parseInt(process.env.PROFILE_INTERVAL || "100")
const base = process.memoryUsage().rss
let rss = 0
let countSamples = 0
const sample = () => {
let memUsage = process.memoryUsage()
if (memUsage.rss > rss) {
rss = memUsage.rss
}
countSamples++
setTimeout(sample, PROFILE_INTERVAL).unref()
}
sample()
process.on("exit", () => {
sample()
const imem = (base / 1000000).toFixed(2)
const tmem = (rss / 1000000).toFixed(2)
const amem = ((rss - base) / 1000000).toFixed(2)
console.info(
`\nmem(total): ${tmem}MB\tmem(init): ${imem}MB\tmem(alloc): ${amem}MB`
)
console.timeEnd("time")
console.info(`samples: ${countSamples} interval: ${PROFILE_INTERVAL}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment