|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +/* |
| 4 | + * timeit: tool for performance testing |
| 5 | + * f: function to be tested |
| 6 | + * n: number of timing runs |
| 7 | + * nchunk: optional number of repetitions per timing run - useful if |
| 8 | + * the function is very fast. Note though that if arg is a function |
| 9 | + * it will not be re-evaluated within the chunk, only before each chunk. |
| 10 | + * arg: optional argument to the function. Can be a function itself |
| 11 | + * to provide a changing input to f |
| 12 | + */ |
| 13 | +window.timeit = function(f, n, nchunk, arg) { |
| 14 | + var times = new Array(n); |
| 15 | + var totalTime = 0; |
| 16 | + var _arg; |
| 17 | + var t0, t1, dt; |
| 18 | + |
| 19 | + for(var i = 0; i < n; i++) { |
| 20 | + if(typeof arg === 'function') _arg = arg(); |
| 21 | + else _arg = arg; |
| 22 | + |
| 23 | + if(nchunk) { |
| 24 | + t0 = performance.now(); |
| 25 | + for(var j = 0; j < nchunk; j++) { f(_arg); } |
| 26 | + t1 = performance.now(); |
| 27 | + dt = (t1 - t0) / nchunk; |
| 28 | + } |
| 29 | + else { |
| 30 | + t0 = performance.now(); |
| 31 | + f(_arg); |
| 32 | + t1 = performance.now(); |
| 33 | + dt = t1 - t0; |
| 34 | + } |
| 35 | + |
| 36 | + times[i] = dt; |
| 37 | + totalTime += dt; |
| 38 | + } |
| 39 | + |
| 40 | + var first = (times[0]).toFixed(4); |
| 41 | + var last = (times[n - 1]).toFixed(4); |
| 42 | + times.sort(); |
| 43 | + var min = (times[0]).toFixed(4); |
| 44 | + var max = (times[n - 1]).toFixed(4); |
| 45 | + var median = (times[Math.ceil(n / 2)]).toFixed(4); |
| 46 | + var mean = (totalTime / n).toFixed(4); |
| 47 | + console.log((f.name || 'function') + ' timing (ms) - min: ' + min + |
| 48 | + ' max: ' + max + |
| 49 | + ' median: ' + median + |
| 50 | + ' mean: ' + mean + |
| 51 | + ' first: ' + first + |
| 52 | + ' last: ' + last |
| 53 | + ); |
| 54 | +}; |
0 commit comments