Last active
September 16, 2017 03:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
and if you want levels of nesting you can use: