Created
May 25, 2020 09:14
-
-
Save pvdz/796350a38fa90851a0ee4aefbbd80072 to your computer and use it in GitHub Desktop.
timeSum, tiny addition to console to measure aggregated time used between two calls and print them and some maintenance around it. ymmv. assumes `console` is global across modules, like it is in nodejs. require once use anywhere
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 { performance } = require("perf_hooks") | |
let running = new Map() | |
let data = new Map() | |
let timeNames = new Set() | |
console.timeSum = function _timeSum(name, callback) { | |
if (running.has(name)) { | |
return console.warn("console.timeSum: name already being recorded:", name) | |
} | |
running.set(name, performance.now()) | |
if (callback) { | |
try { | |
callback() | |
} finally { | |
console.timeSumEnd(name) | |
} | |
} | |
} | |
console.timeSumEnd = function _timeEndSum(name, recordAs = name) { | |
const start = running.get(name) | |
if (start === undefined) { | |
return console.warn("console.timeEndSum: name not being recorded:", name) | |
} | |
running.delete(name) | |
let before = data.get(recordAs) | |
if (before === undefined) before = 0 | |
const delta = performance.now() - start | |
data.set(recordAs, before + delta) | |
timeNames.add(recordAs) | |
} | |
console.timeSumCancel = function _timeSumCancel(name) { | |
// Should this warn if the name does not exist..? | |
running.delete(name) | |
} | |
console.timeSumPrint = function _timeSumPrint() { | |
console.group("timeSum report;") | |
let max = 0 | |
data.forEach((time, name) => { | |
max = Math.max(max, time.toFixed(0).length) | |
}) | |
data.forEach((time, name) => { | |
console.log( | |
"- " + | |
time.toFixed(2).padStart(max + 4, " ") + | |
(timeNames.has(name) ? "ms" : " ") + | |
": " + | |
name | |
) | |
}) | |
console.groupEnd() | |
} | |
console.timeSumReset = function _timeSumClear() { | |
data = new Map() | |
running = new Map() | |
timeNames = new Set() | |
} | |
console.timeSumCount = function _timeSumCount(name, delta = 1) { | |
let before = data.get(name) | |
if (before === undefined) before = 0 | |
data.set(name, before + delta) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment