Timer | JavaScript

ThiccDaddyLOAF

February 5th, 2021 01:14:09 AM

					
class Timer{ start(){ this.startTime = Date.now(); } stop(){ const dt = Date.now() - this.startTime; console.log(dt); return dt; } getExecTime(fun, asynchronous){ return asynchronous ? this.getAsyncExecTime(fun) : this.getSyncExecTime(fun); } getSyncExecTime(fun){ this.start(); fun(); return this.stop(); } async getAsyncExecTime(fun){ this.start(); await fun(); return this.stop(); } static average(fun, numTimes, asynchronous = false){ const times = []; const promises = []; let timer = new Timer(); if(asynchronous){ for(let i = 0; i < numTimes; i++){ timer.getAsyncExecTime(fun); } }else{ for(let i = 0; i < numTimes; i++){ timer.getSyncExecTime(fun); } } return (times => times.reduce(((sum, acc) => sume + acc), 0) / times.length); } static async timeAsync(fun, numTimes){ if(numTimes <= 1) return new Timer().getAsyncExecTime(fun); const promises = []; let timer = new Timer(true); for(let i = 0; i < numTimes; i++){ promises.push(fun().catch((e)=>{})); } try{ await Promise.all(promises).catch((e)=>{}); }catch(e){ //do absolutely nothing } return timer.stop(); } constructor(start = false){ if(start) this.start(); } }

Featured Posts