This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
jslitmus.js
623 lines (532 loc) · 15.1 KB
/
jslitmus.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// jslitmus.js
//
// Copyright (c) 2010, Robert Kieffer, http://broofa.com
// Available under MIT license (http://en.wikipedia.org/wiki/MIT_License)
(function() {
var root = this;
//
// Platform detect
//
var platform = (function() {
// Platform info object
var p = {
name: null,
version: null,
os: null,
description: 'unknown platform',
toString: function() {return this.description;}
};
if (root.navigator) {
var ua = navigator.userAgent;
// Detect OS
var oses = 'Windows|iPhone OS|(?:Intel |PPC )?Mac OS X|Linux';
p.os = new RegExp('((' + oses + ') +[^ \);]*)').test(ua) ? RegExp.$1.replace(/_/g, '.') : null;
// Detect expected names
p.name = /(Chrome|MSIE|Safari|Opera|Firefox|Minefield)/.test(ua) ? RegExp.$1 : null;
// Detect version
if (p.name == 'Opera') {
p.version = opera.name;
} else if (p.name) {
var vre = new RegExp('(Version|' + p.name + ')[ \/]([^ ;]*)');
p.version = vre.test(ua) ? RegExp.$2 : null;
}
} else if (root.process && process.platform) {
// Support node.js (see http://nodejs.org)
p.name = 'node';
p.version = process.version;
p.os = process.platform;
}
// Set the description
var d = [];
if (p.name) d.push(p.name);
if (p.version) d.push(' ' + p.version);
if (p.os) d.push(' on ' + p.os);
if (d.length) p.description = d.join('');
return p;
})();
//
// Context-specific initialization
//
var sys = null, querystring = null;
if (platform.name == 'node') {
sys = require('sys');
querystring = require('querystring');
}
//
// Misc convenience methods
//
function log(msg) {
if (typeof(console) != 'undefined') {
console.log(msg);
} else if (sys) {
sys.log(msg);
}
}
// nil function
function nilf(x) {
return x;
}
// Copy properties
function extend(dst, src) {
for (var k in src) {
dst[k] = src[k];
}
return dst;
}
// Array: apply f to each item in a
function forEach(a, f) {
for (var i = 0, il = (a && a.length); i < il; i++) {
var o = a[i];
f(o, i);
}
}
// Array: return array of all results of f(item)
function map(a, f) {
var o, res = [];
for (var i = 0, il = (a && a.length); i < il; i++) {
var o = a[i];
res.push(f(o, i));
}
return res;
}
// Array: filter out items for which f(item) is falsy
function filter(a, f) {
var o, res = [];
for (var i = 0, il = (a && a.length); i < il; i++) {
var o = a[i];
if (f(o, i)) res.push(o);
}
return res;
}
// Array: IE doesn't have indexOf in some cases
function indexOf(a, o) {
if (a.indexOf) return a.indexOf(o);
for (var i = 0, l = a.length; i < l; i++) if (a[i] === o) return i;
return -1;
}
// Enhanced escape()
function escape2(s) {
s = s.replace(/,/g, '\\,');
s = querystring ? querystring.escape(s) : escape(s);
s = s.replace(/\+/g, '%2b');
s = s.replace(/ /g, '+');
return s;
}
// join(), for objects. Creates url query param-style strings by default
function join(o, delimit1, delimit2) {
var asQuery = !delimit1 && !delimit2;
if (asQuery) {
delimit1 = '&';
delimit2 = '=';
}
var pairs = [];
for (var key in o) {
var value = o[key];
if (asQuery) value = escape2(value);
pairs.push(key + delimit2 + o[key]);
}
return pairs.join(delimit1);
}
// split(), for object strings. Parses url query param strings by default
function split(s, delimit1, delimit2) {
var asQuery = !delimit1 && !delimit2;
if (asQuery) {
s = s.replace(/.*[?#]/, '');
delimit1 = '&';
delimit2 = '=';
}
if (match) {
var o = query.split(delimit1);
for (var i = 0; i < o.length; i++) {
var pair = o[i].split(new RegExp(delimit2 + '+'));
var key = pair.shift();
var value = (asQuery && pair.length > 1) ? pair.join(delimit2) : pair[0];
o[key] = value;
}
}
return o;
}
// Round x to d significant digits
function sig(x, d) {
var exp = Math.ceil(Math.log(Math.abs(x))/Math.log(10)),
f = Math.pow(10, exp-d);
return Math.round(x/f)*f;
}
// Convert x to a readable string version
function humanize(x, sd) {
var ax = Math.abs(x), res;
sd = sd | 4; // significant digits
if (ax == Infinity) {
res = ax > 0 ? 'Infinity' : '-Infinity';
} else if (ax > 1e9) {
res = sig(x/1e9, sd) + 'G';
} else if (ax > 1e6) {
res = sig(x/1e6, sd) + 'M';
} else if (ax > 1e3) {
res = sig(x/1e3, sd) + 'k';
} else if (ax > .01) {
res = sig(x, sd);
} else if (ax > 1e-3) {
res = sig(x/1e-3, sd) + 'm';
} else if (ax > 1e-6) {
res = sig(x/1e-6, sd) + '\u00b5'; // Greek mu
} else if (ax > 1e-9) {
res = sig(x/1e-9, sd) + 'n';
} else {
res = x ? sig(x, sd) : 0;
}
// Turn values like "1.1000000000005" -> "1.1"
res = (res + '').replace(/0{5,}\d*/, '');
return res;
}
// Node.js-inspired event emitter API, with some enhancements.
function EventEmitter() {
var ee = this;
var listeners = {};
extend(ee, {
on: function(e, f) {
if (!listeners[e]) listeners[e] = [];
listeners[e].push(f);
},
removeListener: function(e, f) {
listeners[e] = filter(listeners[e], function(l) {
return l != f;
});
},
removeAllListeners: function(e) {
listeners[e] = [];
},
emit: function(e) {
var args = Array.prototype.slice.call(arguments, 1);
forEach([].concat(listeners[e], listeners['*']), function(l) {
ee._emitting = e;
if (l) l.apply(ee, args);
});
delete ee._emitting;
}
});
}
//
// Test class
//
/**
* Test manages a single test (created with JSLitmus.test())
*/
function Test(name, f) {
var test = this;
// Test instances get EventEmitter API
EventEmitter.call(test);
if (!f) throw new Error('Undefined test function');
if (!/function[^\(]*\(([^,\)]*)/.test(f)) {
throw new Error('"' + name + '" test: Invalid test function');
}
// If the test function takes an argument, we assume it does the iteration
// for us
var isLoop = !!RegExp.$1;
/**
* Reset test state
*/
function reset() {
delete test.count;
delete test.time;
delete test.running;
test.emit('reset', test);
return test;
}
function clone() {
var test = extend(new Test(name, f), test);
return test.reset();
}
/**
* Run the test n times, and use the best results
*/
function bestOf(n) {
var best = null;
while (n--) {
var t = clone();
t.run(null, true);
if (!best || t.period < best.period) {
best = t;
}
}
extend(test, best);
}
/**
* Start running a test. Default is to run the test asynchronously (via
* setTimeout). Can be made synchronous by passing true for 2nd param
*/
function run(count, synchronous) {
count = count || test.INIT_COUNT;
test.running = true;
if (synchronous) {
_run(count, synchronous);
} else {
setTimeout(function() {
_run(count);
}, 1);
}
return test;
}
/**
* Run, for real
*/
function _run(count, noTimeout) {
try {
var start, f = test.f, now, i = count;
// Start the timer
start = new Date();
// Run the test code
test.count = count;
test.time = 0;
test.period = 0;
test.emit('start', test);
if (isLoop) {
// Test code does it's own iteration
f(count);
} else {
// Do the iteration ourselves
while (i--) f();
}
// Get time test took (in secs)
test.time = Math.max(1,new Date() - start)/1000;
// Store iteration count and per-operation time taken
test.count = count;
test.period = test.time/count;
// Do we need to keep running?
test.running = test.time < test.MIN_TIME;
// Publish results
test.emit('results', test);
// Set up for another run, if needed
if (test.running) {
// Use an iteration count that will (we hope) get us close to the
// MAX_COUNT time.
var x = test.MIN_TIME/test.time;
var pow = Math.pow(2, Math.max(1, Math.ceil(Math.log(x)/Math.log(2))));
count *= pow;
if (count > test.MAX_COUNT) {
throw new Error('Max count exceeded. If this test uses a looping function, make sure the iteration loop is working properly.');
}
if (noTimeout) {
_run(count, noTimeout);
} else {
run(count);
}
} else {
test.emit('complete', test);
}
} catch (err) {
log(err);
// Exceptions are caught and displayed in the test UI
test.emit('error', err);
}
return test;
}
/**
* Get the number of operations per second for this test.
*
* @param normalize if true, iteration loop overhead taken into account.
* Note that normalized tests may return Infinity if the
* test time is of the same order as the calibration time.
*/
function getHz(normalize) {
var p = test.period;
// Adjust period based on the calibration test time
if (normalize) {
var cal = test.isLoop ? Test.LOOP_CAL : Test.NOLOOP_CAL;
if (!cal.period) {
// Run calibration if needed
cal.MIN_TIME = .3;
cal.bestOf(3);
}
// Subtract off calibration time. In theory this should never be
// negative, but in practice the calibration times are affected by a
// variety of factors so just clip to zero and let users test for
// getHz() == Infinity
p = Math.max(0, p - cal.period);
}
return sig(1/p, 4);
}
// Set properties that are specific to this instance
extend(test, {
// Test name
name: name,
// Test function
f: f,
// True if the test function does it's own looping (i.e. takes an arg)
isLoop: isLoop,
clone: clone,
run: run,
bestOf: bestOf,
getHz: getHz,
reset: reset
});
// IE7 doesn't do 'toString' or 'toValue' in object enumerations, so set
// it explicitely here.
test.toString = function() {
if (this.time) {
return this.name + ', f = ' +
humanize(this.getHz()) + 'hz (' +
humanize(this.count) + '/' + humanize(this.time) + 'secs)';
} else {
return this.name + ', count = ' + humanize(this.count);
}
};
};
// Set static properties
extend(Test, {
LOOP_CAL: new Test('loop cal', function(count) {while (count--) {}}),
NOLOOP_CAL: new Test('noloop cal', nilf)
});
// Set default property values
extend(Test.prototype, {
// Initial number of iterations
INIT_COUNT: 10,
// Max iterations allowed (used to detect bad looping functions)
MAX_COUNT: 1e9,
// Minimum time test should take to get valid results (secs)
MIN_TIME: 1.0
});
//
// jslitmus
//
// Set up jslitmus context
var jslitmus;
if (platform.name == 'node') {
jslitmus = exports;
} else {
jslitmus = root.jslitmus = {};
}
var tests = [], // test store (all tests added w/ jslitmus.test())
queue = [], // test queue (to be run)
currentTest; // currently runnning test
// jslitmus gets EventEmitter API
EventEmitter.call(jslitmus);
/**
* Create a new test
*/
function test(name, f) {
// Create the Test object
var test = new Test(name, f);
tests.push(test);
// Run the next test if this one finished
test.on('*', function() {
// Forward test events to jslitmus listeners
var args = Array.prototype.slice.call(arguments);
args.unshift(test._emitting);
jslitmus.emit.apply(jslitmus, args);
// Auto-run the next test
if (test._emitting == 'complete') {
currentTest = null;
_nextTest();
}
});
jslitmus.emit('added', test);
return test;
}
/**
* Add all tests to the run queue
*/
function runAll(e) {
forEach(tests, _queueTest);
}
/**
* Remove all tests from the run queue. The current test has to finish on
* it's own though
*/
function stop() {
while (queue.length) {
var test = queue.shift();
}
}
/**
* Run the next test in the run queue
*/
function _nextTest() {
if (!currentTest) {
var test = queue.shift();
if (test) {
currentTest = test;
test.run();
} else {
jslitmus.emit('all_complete');
}
}
}
/**
* Add a test to the run queue
*/
function _queueTest(test) {
if (indexOf(queue, test) >= 0) return;
queue.push(test);
_nextTest();
}
/**
* Generate a Google Chart URL that shows the data for all tests
*/
function getGoogleChart(normalize) {
var chart_title = [
'Operations/second on ' + platform.name,
'(' + platform.version + ' / ' + platform.os + ')'
];
var n = tests.length, markers = [], data = [];
var d, min = 0, max = -1e10;
// Gather test data
var markers = map(tests, function(test, i) {
if (test.count) {
var hz = test.getHz();
var v = hz != Infinity ? hz : 0;
data.push(v);
var label = test.name + '(' + humanize(hz)+ ')';
var marker = 't' + escape2(label) + ',000000,0,' + i + ',10';
max = Math.max(v, max);
return marker;
}
});
if (markers.length <= 0) return null;
// Build labels
var labels = [humanize(min), humanize(max)];
var w = 250, bw = 15;
var bs = 5;
var h = markers.length*(bw + bs) + 30 + chart_title.length*20;
var params = {
chtt: escape(chart_title.join('|')),
chts: '000000,10',
cht: 'bhg', // chart type
chd: 't:' + data.join(','), // data set
chds: min + ',' + max, // max/min of data
chxt: 'x', // label axes
chxl: '0:|' + labels.join('|'), // labels
chsp: '0,1',
chm: markers.join('|'), // test names
chbh: [bw, 0, bs].join(','), // bar widths
// chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient
chs: w + 'x' + h
};
var url = 'http://chart.apis.google.com/chart?' + join(params);
return url;
}
// Public API
extend(jslitmus, {
Test: Test,
platform: platform,
test: test,
runAll: runAll,
getGoogleChart: getGoogleChart
});
// Expose code goodness we've got here, since it's useful, but do so in a way
// that doesn't commit us to supporting it in future versions.
jslitmus.unsupported = {
nilf: nilf,
log: log,
extend: extend,
forEach: forEach,
filter: filter,
map: map,
indexOf: indexOf,
escape2: escape2,
join: join,
split: split,
sig: sig,
humanize: humanize
};
})();