1 function log(text) { 2 document.getElementById("log").innerHTML += text + "\n"; 3 window.scrollTo(0, document.body.height); 4 } 5 6 function loadFile(path) { 7 var xhr = new XMLHttpRequest(); 8 xhr.open("GET", path, false); 9 xhr.send(null); 10 return xhr.responseText; 11 } 12 13 var runCount = -1; 14 var runFunction = function() {}; 15 var completedRuns = -1; // Discard the any runs < 0. 16 var times = []; 17 18 function computeAverage(values) { 19 var sum = 0; 20 for (var i = 0; i < values.length; i++) 21 sum += values[i]; 22 return sum / values.length; 23 } 24 25 function computeMax(values) { 26 var max = values.length ? values[0] : 0; 27 for (var i = 1; i < values.length; i++) { 28 if (max < values[i]) 29 max = values[i]; 30 } 31 return max; 32 } 33 34 function computeMedian(values) { 35 values.sort(function(a, b) { return a - b; }); 36 var len = values.length; 37 if (len % 2) 38 return values[(len-1)/2]; 39 return (values[len/2-1] + values[len/2]) / 2; 40 } 41 42 function computeMin(values) { 43 var min = values.length ? values[0] : 0; 44 for (var i = 1; i < values.length; i++) { 45 if (min > values[i]) 46 min = values[i]; 47 } 48 return min; 49 } 50 51 function computeStdev(values) { 52 var average = computeAverage(values); 53 var sumOfSquaredDeviations = 0; 54 for (var i = 0; i < values.length; ++i) { 55 var deviation = values[i] - average; 56 sumOfSquaredDeviations += deviation * deviation; 57 } 58 return Math.sqrt(sumOfSquaredDeviations / values.length); 59 } 60 61 function logStatistics(times) { 62 log(""); 63 log("avg " + computeAverage(times)); 64 log("median " + computeMedian(times)); 65 log("stdev " + computeStdev(times)); 66 log("min " + computeMin(times)); 67 log("max " + computeMax(times)); 68 } 69 70 function run() { 71 var start = new Date(); 72 for (var i = 0; i < 10; ++i) 73 window.runFunction(); 74 var time = new Date() - start; 75 completedRuns++; 76 if (completedRuns <= 0) { 77 log("Ignoring warm-up run (" + time + ")"); 78 } else { 79 times.push(time); 80 log(time); 81 } 82 if (completedRuns < window.runCount) { 83 window.setTimeout(run, 0); 84 } else { 85 logStatistics(times); 86 } 87 } 88 89 function start(runCount, runFunction) { 90 window.runCount = runCount; 91 window.runFunction = runFunction; 92 93 log("Running " + runCount + " times"); 94 run(); 95 } 96