bench: Add --html to compare script
[platform/upstream/nodejs.git] / benchmark / _bench_timer.js
1 /*
2  * This is a simple addition to allow for higher resolution timers.
3  * It can be used to track time for both synchronous or asynchronous
4  * calls. For synchronous calls pass a callback function like so:
5  *
6  *  var timer = require('./_bench_timer');
7  *
8  *  timer('myTest', function() {
9  *    for (var i = 0; i < 1e6; i++)
10  *      // ... run something here
11  *    }
12  *  });
13  *
14  * For asynchronous timers just pass the name. Then run it again with
15  * the same name to finish it:
16  *
17  *  timer('checkAsync');
18  *  setTimeout(function() {
19  *    timer('checkAsync');
20  *  }, 300);
21  *
22  * When this happens all currently queued benchmarks will be paused
23  * until the asynchronous benchmark has completed.
24  *
25  * If the benchmark has been run with --expose_gc then the garbage
26  * collector will be run between each test.
27  *
28  * The setTimeout delay can also be changed by passing a value to
29  * timer.delay.
30  */
31
32
33 var store = {};
34 var order = [];
35 var maxLength = 0;
36 var processing = false;
37 var asyncQueue = 0;
38 var GCd = typeof gc !== 'function' ? false : true;
39
40 function timer(name, fn) {
41   if (maxLength < name.length)
42     maxLength = name.length;
43   if (!fn) {
44     processing = false;
45     if (!store[name]) {
46       asyncQueue++;
47       store[name] = process.hrtime();
48       return;
49     }
50     displayTime(name, process.hrtime(store[name]));
51     asyncQueue--;
52   } else {
53     store[name] = fn;
54     order.push(name);
55   }
56   if (!processing && asyncQueue <= 0) {
57     processing = true;
58     setTimeout(run, timer.delay);
59   }
60 }
61
62 timer.delay = 100;
63
64 function run() {
65   if (asyncQueue > 0 || order.length <= 0)
66     return;
67   if (GCd) gc();
68   setTimeout(function() {
69     var name = order.shift();
70     var fn = store[name];
71     var ini = process.hrtime();
72     fn();
73     ini = process.hrtime(ini);
74     displayTime(name, ini);
75     run();
76   }, timer.delay);
77 }
78
79 function displayTime(name, ini) {
80   name += ': ';
81   while (name.length < maxLength + 2)
82     name += ' ';
83   console.log(name + '%s \u00b5s',
84               (~~((ini[0] * 1e6) + (ini[1] / 1e3)))
85                 .toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
86 }
87
88 module.exports = timer;