Remove NodeListsNodeData when it's no longer needed
[WebKit-https.git] / PerformanceTests / resources / runner.js
1 // There are tests for computeStatistics() located in LayoutTests/fast/harness/perftests
2
3 // We need access to console.memory for the memory measurements
4 if (window.internals)
5     internals.settings.setMemoryInfoEnabled(true);
6
7 if (window.testRunner) {
8     testRunner.waitUntilDone();
9     testRunner.dumpAsText();
10 }
11
12 (function () {
13     var logLines = null;
14     var completedIterations = -1;
15     var callsPerIteration = 1;
16     var currentTest = null;
17     var results = [];
18     var jsHeapResults = [];
19     var mallocHeapResults = [];
20     var iterationCount = undefined;
21
22     var PerfTestRunner = {};
23
24     // To make the benchmark results predictable, we replace Math.random with a
25     // 100% deterministic alternative.
26     PerfTestRunner.randomSeed = PerfTestRunner.initialRandomSeed = 49734321;
27
28     PerfTestRunner.resetRandomSeed = function() {
29         PerfTestRunner.randomSeed = PerfTestRunner.initialRandomSeed
30     }
31
32     PerfTestRunner.random = Math.random = function() {
33         // Robert Jenkins' 32 bit integer hash function.
34         var randomSeed = PerfTestRunner.randomSeed;
35         randomSeed = ((randomSeed + 0x7ed55d16) + (randomSeed << 12))  & 0xffffffff;
36         randomSeed = ((randomSeed ^ 0xc761c23c) ^ (randomSeed >>> 19)) & 0xffffffff;
37         randomSeed = ((randomSeed + 0x165667b1) + (randomSeed << 5))   & 0xffffffff;
38         randomSeed = ((randomSeed + 0xd3a2646c) ^ (randomSeed << 9))   & 0xffffffff;
39         randomSeed = ((randomSeed + 0xfd7046c5) + (randomSeed << 3))   & 0xffffffff;
40         randomSeed = ((randomSeed ^ 0xb55a4f09) ^ (randomSeed >>> 16)) & 0xffffffff;
41         PerfTestRunner.randomSeed = randomSeed;
42         return (randomSeed & 0xfffffff) / 0x10000000;
43     };
44
45     PerfTestRunner.now = window.performance && window.performance.now ? function () { return window.performance.now(); } : Date.now;
46
47     PerfTestRunner.logInfo = function (text) {
48         if (!window.testRunner)
49             this.log(text);
50     }
51
52     PerfTestRunner.loadFile = function (path) {
53         var xhr = new XMLHttpRequest();
54         xhr.open("GET", path, false);
55         xhr.send(null);
56         return xhr.responseText;
57     }
58
59     PerfTestRunner.computeStatistics = function (times, unit) {
60         var data = times.slice();
61
62         // Add values from the smallest to the largest to avoid the loss of significance
63         data.sort(function(a,b){return a-b;});
64
65         var middle = Math.floor(data.length / 2);
66         var result = {
67             min: data[0],
68             max: data[data.length - 1],
69             median: data.length % 2 ? data[middle] : (data[middle - 1] + data[middle]) / 2,
70         };
71
72         // Compute the mean and variance using Knuth's online algorithm (has good numerical stability).
73         var squareSum = 0;
74         result.values = times;
75         result.mean = 0;
76         for (var i = 0; i < data.length; ++i) {
77             var x = data[i];
78             var delta = x - result.mean;
79             var sweep = i + 1.0;
80             result.mean += delta / sweep;
81             squareSum += delta * (x - result.mean);
82         }
83         result.variance = data.length <= 1 ? 0 : squareSum / (data.length - 1);
84         result.stdev = Math.sqrt(result.variance);
85         result.unit = unit || "ms";
86
87         return result;
88     }
89
90     PerfTestRunner.logStatistics = function (values, unit, title) {
91         var statistics = this.computeStatistics(values, unit);
92         this.log("");
93         this.log(title);
94         if (statistics.values)
95             this.log("values " + statistics.values.join(", ") + " " + statistics.unit);
96         this.log("avg " + statistics.mean + " " + statistics.unit);
97         this.log("median " + statistics.median + " " + statistics.unit);
98         this.log("stdev " + statistics.stdev + " " + statistics.unit);
99         this.log("min " + statistics.min + " " + statistics.unit);
100         this.log("max " + statistics.max + " " + statistics.unit);
101     }
102
103     function getUsedMallocHeap() {
104         var stats = window.internals.mallocStatistics();
105         return stats.committedVMBytes - stats.freeListBytes;
106     }
107
108     function getUsedJSHeap() {
109         return console.memory.usedJSHeapSize;
110     }
111
112     PerfTestRunner.gc = function () {
113         if (window.GCController)
114             window.GCController.collect();
115         else {
116             function gcRec(n) {
117                 if (n < 1)
118                     return {};
119                 var temp = {i: "ab" + i + (i / 100000)};
120                 temp += "foo";
121                 gcRec(n-1);
122             }
123             for (var i = 0; i < 1000; i++)
124                 gcRec(10);
125         }
126     };
127
128     function logInDocument(text) {
129         if (!document.getElementById("log")) {
130             var pre = document.createElement("pre");
131             pre.id = "log";
132             document.body.appendChild(pre);
133         }
134         document.getElementById("log").innerHTML += text + "\n";
135         window.scrollTo(0, document.body.height);
136     }
137
138     PerfTestRunner.log = function (text) {
139         if (logLines)
140             logLines.push(text);
141         else
142             logInDocument(text);
143     }
144
145     function logFatalError(text) {
146         PerfTestRunner.log(text);
147         finish();
148     }
149
150     function start(test, runner) {
151         if (!test) {
152             logFatalError("Got a bad test object.");
153             return;
154         }
155         currentTest = test;
156         iterationCount = test.iterationCount || 20;
157         logLines = window.testRunner ? [] : null;
158         PerfTestRunner.log("Running " + iterationCount + " times");
159         if (test.doNotIgnoreInitialRun)
160             completedIterations++;
161         if (runner)
162             scheduleNextRun(runner);
163     }
164
165     function scheduleNextRun(runner) {
166         PerfTestRunner.gc();
167         window.setTimeout(function () {
168             try {
169                 if (currentTest.setup)
170                     currentTest.setup();
171
172                 var measuredValue = runner();
173             } catch (exception) {
174                 logFatalError("Got an exception while running test.run with name=" + exception.name + ", message=" + exception.message);
175                 return;
176             }
177
178             completedIterations++;
179
180             try {
181                 ignoreWarmUpAndLog(measuredValue);
182             } catch (exception) {
183                 logFatalError("Got an exception while logging the result with name=" + exception.name + ", message=" + exception.message);
184                 return;
185             }
186
187             if (completedIterations < iterationCount)
188                 scheduleNextRun(runner);
189             else
190                 finish();
191         }, 0);
192     }
193
194     function ignoreWarmUpAndLog(measuredValue) {
195         var labeledResult = measuredValue + " " + PerfTestRunner.unit;
196         if (completedIterations <= 0)
197             PerfTestRunner.log("Ignoring warm-up run (" + labeledResult + ")");
198         else {
199             results.push(measuredValue);
200             if (window.internals && !currentTest.doNotMeasureMemoryUsage) {
201                 jsHeapResults.push(getUsedJSHeap());
202                 mallocHeapResults.push(getUsedMallocHeap());
203             }
204             PerfTestRunner.log(labeledResult);
205         }
206     }
207
208     function finish() {
209         try {
210             if (currentTest.description)
211                 PerfTestRunner.log("Description: " + currentTest.description);
212             PerfTestRunner.logStatistics(results, PerfTestRunner.unit, "Time:");
213             if (jsHeapResults.length) {
214                 PerfTestRunner.logStatistics(jsHeapResults, "bytes", "JS Heap:");
215                 PerfTestRunner.logStatistics(mallocHeapResults, "bytes", "Malloc:");
216             }
217             if (logLines)
218                 logLines.forEach(logInDocument);
219             if (currentTest.done)
220                 currentTest.done();
221         } catch (exception) {
222             logInDocument("Got an exception while finalizing the test with name=" + exception.name + ", message=" + exception.message);
223         }
224
225         if (window.testRunner)
226             testRunner.notifyDone();
227     }
228
229     PerfTestRunner.iterationCount = function () {
230         return iterationCount;
231     }
232
233     PerfTestRunner.prepareToMeasureValuesAsync = function (test) {
234         PerfTestRunner.unit = test.unit;
235         start(test);
236     }
237
238     PerfTestRunner.measureValueAsync = function (measuredValue) {
239         completedIterations++;
240
241         try {
242             ignoreWarmUpAndLog(measuredValue);
243         } catch (exception) {
244             logFatalError("Got an exception while logging the result with name=" + exception.name + ", message=" + exception.message);
245             return;
246         }
247
248         if (completedIterations >= iterationCount)
249             finish();
250     }
251
252     PerfTestRunner.measureTime = function (test) {
253         PerfTestRunner.unit = "ms";
254         start(test, measureTimeOnce);
255     }
256
257     function measureTimeOnce() {
258         var start = PerfTestRunner.now();
259         var returnValue = currentTest.run();
260         var end = PerfTestRunner.now();
261
262         if (returnValue - 0 === returnValue) {
263             if (returnValue < 0)
264                 PerfTestRunner.log("runFunction returned a negative value: " + returnValue);
265             return returnValue;
266         }
267
268         return end - start;
269     }
270
271     PerfTestRunner.measureRunsPerSecond = function (test) {
272         PerfTestRunner.unit = "runs/s";
273         start(test, measureRunsPerSecondOnce);
274     }
275
276     function measureRunsPerSecondOnce() {
277         var timeToRun = 750;
278         var totalTime = 0;
279         var numberOfRuns = 0;
280
281         while (totalTime < timeToRun) {
282             totalTime += callRunAndMeasureTime(callsPerIteration);
283             numberOfRuns += callsPerIteration;
284             if (completedIterations < 0 && totalTime < 100)
285                 callsPerIteration = Math.max(10, 2 * callsPerIteration);
286         }
287
288         return numberOfRuns * 1000 / totalTime;
289     }
290
291     function callRunAndMeasureTime(callsPerIteration) {
292         var startTime = PerfTestRunner.now();
293         for (var i = 0; i < callsPerIteration; i++)
294             currentTest.run();
295         return PerfTestRunner.now() - startTime;
296     }
297
298
299     PerfTestRunner.measurePageLoadTime = function(test) {
300         test.run = function() {
301             var file = PerfTestRunner.loadFile(test.path);
302             if (!test.chunkSize)
303                 this.chunkSize = 50000;
304
305             var chunks = [];
306             // The smaller the chunks the more style resolves we do.
307             // Smaller chunk sizes will show more samples in style resolution.
308             // Larger chunk sizes will show more samples in line layout.
309             // Smaller chunk sizes run slower overall, as the per-chunk overhead is high.
310             var chunkCount = Math.ceil(file.length / this.chunkSize);
311             for (var chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++) {
312                 var chunk = file.substr(chunkIndex * this.chunkSize, this.chunkSize);
313                 chunks.push(chunk);
314             }
315
316             PerfTestRunner.logInfo("Testing " + file.length + " byte document in " + chunkCount + " " + this.chunkSize + " byte chunks.");
317
318             var iframe = document.createElement("iframe");
319             document.body.appendChild(iframe);
320
321             iframe.sandbox = '';  // Prevent external loads which could cause write() to return before completing the parse.
322             iframe.style.width = "600px"; // Have a reasonable size so we're not line-breaking on every character.
323             iframe.style.height = "800px";
324             iframe.contentDocument.open();
325
326             for (var chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
327                 iframe.contentDocument.write(chunks[chunkIndex]);
328                 // Note that we won't cause a style resolve until we've encountered the <body> element.
329                 // Thus the number of chunks counted above is not exactly equal to the number of style resolves.
330                 if (iframe.contentDocument.body)
331                     iframe.contentDocument.body.clientHeight; // Force a full layout/style-resolve.
332                 else if (iframe.documentElement.localName == 'html')
333                     iframe.contentDocument.documentElement.offsetWidth; // Force the painting.
334             }
335
336             iframe.contentDocument.close();
337             document.body.removeChild(iframe);
338         };
339
340         PerfTestRunner.measureTime(test);
341     }
342
343     window.PerfTestRunner = PerfTestRunner;
344 })();