forked from xk/nodeSnippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTester.js
89 lines (76 loc) · 1.8 KB
/
Tester.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
/*
Speed Tester
Uso:
tester(functionToTest)
tester.stop() or tester() stops tester
*/
var tester= (function () {
var acumulador= 0;
var kTargetT;
var fooLoops, fooTime= 0;
var ctr= 0;
function foo () {}
function display (t, f) {
var a, b;
var t= ((t[0]/ t[1])- fooTime);
if (t<0) t= 0;
if (t >= 1e3) {
a= (t/1e3).toFixed(2);
b= "s";
} else if (t >= 1) {
a= (t).toFixed(2);
b= "ms";
} else if (t >= 1e-3) {
a= (t*1e3).toFixed(2);
b= "µs";
} else {
a= (t*1e6).toFixed(1);
b= "ns";
}
return [t, a, b, f.name];
}
function tester (f, ms) {
kTargetT= ms ? Math.floor(Math.abs(ms)) : 99;
if (!f || typeof f !== "function") return;
var t;
if (!fooTime) {
t= tester.calibrar();
fooTime= 0;
console.log("FooTime -> "+ display(t, foo));
fooTime= t[0]/t[1];
}
console.log( display(calibrar(f), f) );
}
tester.calibrar= function () {
var t= calibrar(foo, 33);
fooTime= t[0]/t[1];
return t;
}
function time (f, loops) {
var n= loops, t= +new Date();
while (n--) f();
return [+new Date()- t, loops];
}
function calibrar (f, ms) {
ms= ms || kTargetT;
var k, t, loops= 1;
while ((t= time(f, loops))[0] < ms) {
if ((k= ms/(t[0]+1)) < 1) break;
loops= Math.floor(1.1* loops* k);
//console.log([loops, t[0]]);
}
//loops= Math.floor(loops* (ms/ t[0]));
if (loops < 1) loops= 1;
//console.log([t[0], t[1]]);
return t;
}
return tester;
})();
var i= 0;
function a () { ++i; ++i; ++i; ++i; ++i; ++i; ++i; ++i; ++i; ++i; i= 0; }
var list= [a];
process.nextTick(function f () {
tester(function x () { a() });
tester(function y () { list[0]() });
process.nextTick(f);
});