-
Notifications
You must be signed in to change notification settings - Fork 25.3k
/
micro_bench.ts
71 lines (67 loc) · 2.11 KB
/
micro_bench.ts
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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const performance = require('perf_hooks').performance;
interface Benchmark {
(versionName: string): Profile;
report(fn?: (report: string) => void): void;
}
interface Profile {
(): boolean;
profileName: string;
run(): boolean;
bestTime: number;
}
export function createBenchmark(
benchmarkName: string, iterationCount: number, runs: number = 50): Benchmark {
const profiles: Profile[] = [];
const benchmark = function Benchmark(profileName: string): Profile {
let iterationCounter: number = iterationCount;
const profile: Profile = function Profile() {
if (iterationCounter === 0) {
iterationCounter = iterationCount;
return false;
} else {
iterationCounter--;
return true;
}
} as Profile;
let lastTimestamp = 0;
let runCount = runs;
profile.run = function() {
const now = performance.now();
if (lastTimestamp !== 0) {
const time = now - lastTimestamp;
profile.bestTime = Math.min(profile.bestTime, time);
}
lastTimestamp = now;
if (runCount === 0) {
runCount = runs;
return false;
} else {
runCount--;
return true;
}
};
profile.profileName = profileName;
profile.bestTime = Number.MAX_SAFE_INTEGER;
profiles.push(profile);
return profile;
} as Benchmark;
benchmark.report = function(fn?: (report: string) => void) {
setTimeout(() => {
const fastest = profiles.reduce((previous: Profile, current: Profile) => {
return (previous.bestTime < current.bestTime) ? previous : current;
});
(fn || console.log)(`Benchmark: ${benchmarkName}\n${profiles.map((profile: Profile) => {
const percent = (100 - profile.bestTime / fastest.bestTime * 100).toFixed(0);
return profile.profileName + ': ' + profile.bestTime.toFixed(0) + ` us(${percent} %) `;
}).join('\n')}`);
});
};
return benchmark;
}