Created
March 10, 2020 22:56
-
-
Save jasonklotzer/bdcd710ccecfb751d7eeb3457476de1b to your computer and use it in GitHub Desktop.
Simple and compact NodeJS performance marking class.
This file contains 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 util = require('util'); | |
const HOT_SPOT_MIN = 100; // amount in ms to determine if there's a hot spot | |
function getStackLine(rewind) { | |
const stackRewind = rewind || 0; | |
const stack = new Error().stack; | |
const line0 = stack.split('\n')[stackRewind + 1]; | |
const sub0 = line0.indexOf('/'); | |
const sub1 = line0.lastIndexOf(':'); | |
return line0.substring(sub0, sub1); | |
} | |
const perfObj = function constructor(id, name) { | |
this.id = id || Math.floor(Math.random() * 10000); | |
this.name = name || `perf_${this.id}`; | |
this.start = Date.now(); | |
this.stack = [{ ref: getStackLine(2), ts: 0, name: 'create' }]; | |
this.length = 1; | |
}; | |
perfObj.prototype.addRef = function addRef(name) { | |
const ticks = Date.now() - this.start; | |
const entry = { ref: getStackLine(2), ts: ticks }; | |
if (name) { | |
entry.name = name; | |
} | |
if (ticks - this.stack[this.stack.length - 1].ts > HOT_SPOT_MIN) { | |
entry.hot = true; | |
} | |
this.stack.push(entry); | |
this.length = this.stack.length; | |
}; | |
perfObj.prototype.print = function print() { | |
// TODO: Allow summary | |
const output = util.inspect(this.get(), { showHidden: false, depth: null, colors: true }); | |
console.log(output); | |
}; | |
perfObj.prototype.get = function get() { | |
return { id: this.id, name: this.name, start: this.start, stack: this.stack }; | |
}; | |
module.exports = perfObj; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment