Skip to content

Instantly share code, notes, and snippets.

@zzzzBov
Last active September 16, 2017 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzzzBov/de08a1ba791820ff5fffd6fb1eb63620 to your computer and use it in GitHub Desktop.
Save zzzzBov/de08a1ba791820ff5fffd6fb1eb63620 to your computer and use it in GitHub Desktop.
A small script to profile JS and dump the data to the console.
class Profiler {
constructor (name) {
this._name = name
this._profiles = []
this._activeProfiles = this._profiles
}
profile (name, fn) {
if (typeof name !== 'string') {
throw new TypeError('"name" must be a string')
}
if (typeof fn !== 'function') {
throw new TypeError('"fn" must be a function')
}
const profile = new Profile(name)
const existingProfiles = this._activeProfiles
existingProfiles.push(profile)
this._activeProfiles = profile.profiles
const start = performance.now()
try {
return fn()
} finally {
const end = performance.now()
profile.delta = end - start
this._activeProfiles = existingProfiles
}
}
log () {
const logProfile = profile => {
const display = `${profile.name}: ${profile.delta}ms`
if (profile.profiles.length) {
console.groupCollapsed(display)
profile.profiles.forEach(logProfile)
console.groupEnd()
} else {
console.log(display)
}
}
console.groupCollapsed(this._name)
this._profiles.forEach(logProfile)
console.groupEnd()
}
}
class Profile {
constructor (name) {
this.name = name
this.profiles = []
this.delta = null
}
}
// Example Usage
const p = new Profiler('Profiler Example 1')
const a = []
p.profile('Outer loop', () => {
for (let i = 0; i < 10; i++) {
p.profile(`Inner loop ${i}`, () => {
for (let j = 0; j < 10; j++) {
a.push([i, j])
}
})
}
})
const p2 = new Profiler('Profiler Example 2')
p.profile('Profiling a profiler', () => {
p2.profile('Profiling a noop', () => {})
})
p.log()
p2.log()
@zzzzBov
Copy link
Author

zzzzBov commented Sep 16, 2017

I wrote this because it seemed like a nifty concept for being able to store JS perf data, but in general profiling can be done with:

try {
  console.time('test')
  // ...do stuff...
} finally {
  console.timeEnd('test')
}

and if you want levels of nesting you can use:

try {
  console.groupCollapsed('test')
  console.time('test')
  // ...do stuff...
} finally {
  console.timeEnd('test')
  console.groupEnd()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment