Last active
August 29, 2015 14:11
-
-
Save rohozhnikoff/8b2079f926874663cf44 to your computer and use it in GitHub Desktop.
Function.prototype.perf (just for concept)
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
_ = require('underscore-contrib') | |
# ------------------------------------------ Helpers | |
middle = (x, y) -> (x + y) / 2 | |
getter = _.curry2(_.flip(_.nth)) | |
# ------------------------------------------ Perf definition | |
Function.prototype.perf = do -> | |
logs = {} | |
sFrom = getter(0) | |
msFrom = getter(1) | |
middleFromTime = (x, y) -> | |
return [ | |
middle sFrom(x), sFrom(y) | |
middle msFrom(x), msFrom(y) | |
] | |
formatTime = (time) -> "#{sFrom(time)}s #{msFrom(time)/1000000}ms" | |
id = 0 | |
return -> | |
funcID = id++ | |
logs[funcID] = [] | |
orig = @ | |
return -> | |
from = process.hrtime() | |
results = orig.apply(@, arguments) | |
endTime = process.hrtime(from) | |
logsArray = logs[funcID] | |
logsArray.push(endTime) | |
middleTime = logsArray.reduce(middleFromTime, logsArray[0]) | |
console.log('Execution time:', formatTime(endTime), ' //', 'Middle time:', formatTime(middleTime)) | |
return results | |
# ------------------------------------------ Example | |
do -> | |
start = 3000 | |
maxV = start + 1 | |
getRandom = (acc, max) -> | |
while acc.indexOf(random) isnt -1 | |
random = Math.floor(Math.random() * max) + 1 | |
random | |
randomize = ((acc, l, max) -> | |
if l < 0 then acc else randomize(acc.concat([getRandom(acc, max)]), l - 1, max) | |
) | |
custom = (-> randomize([], start, maxV)).perf() | |
custom() | |
custom() | |
custom() | |
custom() | |
### response like: | |
Execution time: 0s 251.843461ms // Middle time: 0s 251.843461ms | |
Execution time: 0s 341.344683ms // Middle time: 0s 296.594072ms | |
Execution time: 0s 259.171552ms // Middle time: 0s 277.882812ms | |
Execution time: 0s 275.119679ms // Middle time: 0s 276.5012455ms | |
### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Function.prototype.perf === Function::perf