Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Created April 21, 2021 08:37
Show Gist options
  • Save mholtzhausen/7ce0d9d20236bbd27b2307f5e4c8e570 to your computer and use it in GitHub Desktop.
Save mholtzhausen/7ce0d9d20236bbd27b2307f5e4c8e570 to your computer and use it in GitHub Desktop.
Simple timer function
const {start, measure, create} = require('./timer.js')
const MAX=1000
var seed = Math.random()*1000;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
start('hello')
let to1 = random()*MAX
let to2 = random()*MAX
setTimeout(()=>{
console.log(`task hello took ${measure('hello')}ms (${to1})`)
},to1)
let bye = create('bye')
setTimeout(()=>{
console.log(`task bye took ${bye.measure()}ms (${to2})`)
},to2)
const { performance } = require('perf_hooks')
class TimerError extends Error {}
const timers={}
function start(name){
timers[name] = performance.now()
return timers[name]
}
function measure(name){
if(!(name in timers)) throw new TimerError(`Timer with name '${name}' was never started.`)
return performance.now() - timers[name]
}
/**
* Create a named timer
*
* @param {String} name The name of the timer
* @returns {Object}
*/
function create(name){
start(name)
return {
start(){ return start(name) },
measure(){ return measure(name) },
}
}
module.exports = {
create,
start,
measure
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment