Skip to content

Instantly share code, notes, and snippets.

@evilive3000
Created October 10, 2018 12:53
Show Gist options
  • Save evilive3000/6d839600595b379b6ee92f7fddfa74fa to your computer and use it in GitHub Desktop.
Save evilive3000/6d839600595b379b6ee92f7fddfa74fa to your computer and use it in GitHub Desktop.
const history = Array(1500);
let history_total = 0;
const MDELAY_MS = 1;
let counter = 0;
function measure() {
setTimeout((start) => {
const diff = process.hrtime(start);
const lag = Math.max(0, diff[0] * 1e3 + diff[1] / 1e6 - MDELAY_MS);
const index = counter++ % history.length;
history[index] = lag;
history_total += lag;
}, MDELAY_MS, process.hrtime());
}
let timeout = (function test() {
setTimeout(() => {
measure();
timeout = test();
}, 150 + Math.random() * 100);
})();
module.exports = function lagstats() {
const sorted = history.filter(v => typeof v != 'undefined').sort();
const N = sorted.length;
const sum = sorted.reduce((s, v) => s + v, 0);
const mean = sum / N;
const sd = Math.sqrt(sorted.reduce((s, v) => s + Math.pow(v - mean, 2), 0) / N);
const perc = {
50: sorted[Math.floor(N * .50) - 1],
90: sorted[Math.floor(N * .90) - 1],
95: sorted[Math.floor(N * .95) - 1],
98: sorted[Math.floor(N * .98) - 1],
99: sorted[Math.floor(N * .99) - 1],
100: sorted[N - 1],
};
return {mean, sd, perc, total: history_total};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment