818
Du
dustymarkdown / files
dustymarkdown / node_modules / dust / benchmark / uubench.js
2.4 KB
1(function(uubench){ 2 3function Bench(id, test, options, callback) { 4 this.id = id; 5 this.options = options; 6 this.test = test; 7 this.loop = test.length > 1; 8 this.callback = callback; 9} 10 11Bench.prototype.run = function(iter) { 12 var self = this, fn = self.test, 13 checkfn = self.options.type === "adaptive" ? adaptive : fixed, 14 i = iter, pend = i, 15 min = self.options.min, start; 16 17 if (self.loop) { 18 pend = 1; 19 start = new Date(); 20 fn(checkfn, i); 21 } else { 22 start = new Date(); 23 while (i--) { 24 fn(checkfn); 25 } 26 } 27 28 function fixed() { 29 if (--pend === 0) { 30 var elapsed = new Date() - start; 31 self.callback({iterations: iter, elapsed: elapsed}); 32 } 33 } 34 35 function adaptive() { 36 if (--pend === 0) { 37 var elapsed = new Date() - start; 38 if (elapsed < min) { 39 self.run(iter*2); 40 } else { 41 self.callback({iterations: iter, elapsed: elapsed}); 42 } 43 } 44 } 45} 46 47uubench.Bench = Bench; 48 49uubench.defaults = { 50 type: "adaptive", // adaptive or fixed 51 iterations: 10, // starting iterations 52 min: 100, // minimum run time (ms) - adaptive only 53 delay: 100 // delay between tests (ms) 54} 55 56function Suite(opts) { 57 for (var key in uubench.defaults) { 58 if (opts[key] === undefined) { 59 opts[key] = uubench.defaults[key]; 60 } 61 } 62 this.options = opts; 63 this.tests = []; 64} 65 66Suite.prototype.bench = function(name, fn) { 67 var self = this; 68 self.tests.push(new Bench(name, fn, this.options, function(stats) { 69 self.emit("result", name, stats); 70 self.pending--; 71 self.check(); 72 })); 73} 74 75Suite.prototype.run = function() { 76 if (this.pending) return; 77 var self = this, len = self.tests.length; 78 self.emit("start", self.tests); 79 self.start = new Date().getTime(); 80 self.pending = len; 81 for (var i=0; i<len; i++) { 82 self.runOne(i); 83 } 84} 85 86Suite.prototype.runOne = function(idx) { 87 var self = this; 88 setTimeout(function() { 89 self.tests[idx].run(self.options.iterations); 90 }, self.options.delay); 91} 92 93Suite.prototype.check = function() { 94 if (this.pending) return; 95 this.emit("done", new Date().getTime() - this.start); 96} 97 98Suite.prototype.emit = function(type) { 99 var event = this.options[type]; 100 if (event) { 101 event.apply(this, Array.prototype.slice.call(arguments, 1)); 102 } 103} 104 105uubench.Suite = Suite; 106 107})(typeof exports !== 'undefined' ? exports : window.uubench = {});