Skip to content

Instantly share code, notes, and snippets.

@seognil
Created February 7, 2018 04:55
Show Gist options
  • Save seognil/1b4ca6bfb109d153c94d11bdb2bcab2e to your computer and use it in GitHub Desktop.
Save seognil/1b4ca6bfb109d153c94d11bdb2bcab2e to your computer and use it in GitHub Desktop.
jsperf, test your function performance in browser
;(function () {
// * ---------------------------------------------------------------- tester
var p = performance
function loopTest(fn) {
var count = 1
var time = 0
while (time < 100) {
count *= 10
time = loopTime(fn, count)
}
count = ~~(1000 / time * count)
time = loopTime(fn, count)
return (~~(1000 / time * count))
}
function loopTime(fn, n) {
var time = p.now()
while (n-- > 0) {
fn()
}
return p.now() - time
}
// * ---------------------------------------------------------------- tool
function toThousands(num) {
return num.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,')
}
// * ---------------------------------------------------------------- exports
window.jsperf = function (fnSet) {
fnSet = (typeof fnSet == "function") ? {fn: fnSet} : fnSet
var list = []
// * Do an empty loop, because the first loop is super fast somehow
console.log("starting...")
loopTest(function () {})
for (var label in fnSet) {
var fn = fnSet[label]
if (typeof fn == "function") {
console.log("testing... " + label)
var count = loopTest(fn)
list.push({
"label": label,
"fn": "" + fn,
"ops/sec": count,
"ops/sec (thousands)": toThousands(count),
})
}
}
list = list.sort(function (a, b) {
return b["ops/sec"] - a["ops/sec"]
})
var table = {}
list.forEach(function (e) {
table[e.label] = e
})
console.table(table, ["ops/sec (thousands)", "fn", "ops/sec"])
}
// * ----------------------------------------------------------------
})();
var set = {
now1: performance.now.bind(performance),
now2: () => performance.now(),
now3: Date.now,
now4: () => Date.now(),
}
jsperf(set)
jsperf(Date.now)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment