UNPKG

chronode

Version:

Chronometer to measure nodejs algos.

1 lines 2.07 kB
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:"",Red:"",Green:"",Yellow:"",Blue:"",Magenta:"",Cyan:"",White:"",bgBlack:"",bgRed:"",bgGreen:"",bgYellow:"",bgBlue:"",bgMagenta:"",bgCyan:"",bgWhite:""}[e]+t+""}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))}};