chronode
Version:
Chronometer to measure nodejs algos.
1 lines • 2.07 kB
JavaScript
function formatFullTime(e){let t=moment(e).toObject();return t.hours+":"+ +t.minutes+":"+t.seconds+"."+t.milliseconds}function formatTime(e){let t=moment.duration(e),o="";return t.hours()&&(o+=" "+colorize("Green",t.hours().toString())+"h"),t.minutes()&&(o+=" "+colorize("Green",t.minutes().toString())+"m"),t.seconds()&&(o+=" "+colorize("Green",t.seconds().toString())+"s"),t.milliseconds()&&(o+=" "+colorize("Green",t.milliseconds().toString())+"ms"),o}function colorize(e,t){return{Black:"[30m",Red:"[31m",Green:"[32m",Yellow:"[33m",Blue:"[34m",Magenta:"[35m",Cyan:"[36m",White:"[37m",bgBlack:"[40m",bgRed:"[41m",bgGreen:"[42m",bgYellow:"[43m",bgBlue:"[44m",bgMagenta:"[45m",bgCyan:"[46m",bgWhite:"[47m"}[e]+t+"[0m"}const moment=require("moment");module.exports={measurements:[],getMeasurement(e){let t=this.measurements.find(t=>t.name===e);if(!t)throw new Error("This measurement ("+e+") doesn't exist.");return t},start(e){this.measurements.push({name:e,startedAt:Date.now(),steps:[],running:!0})},step(e,t){if(!t)throw new Error("Missing parameter stepName");this.getMeasurement(e).steps.push({name:t,time:Date.now()})},stop(e,t){if(!t)throw new Error("Missing parameter stepName");const o=Date.now(),n=this.getMeasurement(e);n.steps.push({name:t,time:o}),n.stoppedAt=o,n.running=!1},print(e){if(!e)throw new Error("Missing parameter measurementName");const t=this.getMeasurement(e),o=t.stoppedAt-t.startedAt;if(t.running)throw new Error("Please stop the measurement before printing it.");console.log(" **************************************"),console.log(" * Measurement result *"),console.log(" **************************************"),console.log(""),console.log(" # "+e),console.log(" + Started at : "+formatFullTime(t.startedAt)),console.log(" + Stopped at : "+formatFullTime(t.stoppedAt)),t.steps.forEach((e,n)=>{let s=n>0?e.time-t.steps[n-1].time:e.time-t.startedAt,r=" > "+e.name+" : "+formatTime(s);r+=" ("+colorize("Blue",(s/o*100).toFixed(1))+"%)",console.log(r)}),console.log(" + Total time : "+formatTime(o))}};