Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Benchmark class for minor performance testing.
_avg = (items) ->
sum = 0
sum += item for item in items
sum / items.length
class Benchmark
constructor: (@functions,@maxSampling) ->
@check()
check: () ->
for fn in @functions
throw "invalid function exist" if typeof fn isnt 'function'
throw "anonymous function not allowed" if fn.name in [undefined ,null,'']
run: (sampling) ->
@maxSampling = sampling or @maxSampling
@result = result = {}
max = @maxSampling
for fn in @functions
samples = max
startTime = (new Date()).getTime()
while samples--
fn()
result[fn.name] = (new Date()).getTime() - startTime
return result
average: (times, sampling) ->
@times = times = unless times then 1 else Math.max(times,1)
averages = []
while times--
averages.push @run(sampling)
@completeResult = averages
result = @result = {}
for average in averages
for entry of average
unless result[entry]
result[entry] = [average[entry]]
else
result[entry].push average[entry]
for entry of result
result[entry] = _avg(result[entry])
# tests
a = true;
class tripleEquals
constructor: () -> `a === true`
class tripleNotEquals
constructor: () -> `a !== true`
class equals
constructor: () -> `a == true`
class notEquals
constructor: () -> `a != true`
bm = new Benchmark([doubleEquals,tripleEquals,tripleEqualsFalse,doubleEqualsFalse])
bm.average(30,10000)
console.log(bm)
a =
x: 1
y: 2
class forIn
constructor: () -> if('x' of a) then true else false
class access
constructor: () -> if(a.x) then true else false
bm = new Benchmark([access,forIn])
bm.average(4,10000)
console.log(bm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.