-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathStopwatch.ts
49 lines (40 loc) · 1.2 KB
/
Stopwatch.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
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
import { TimeSpan } from "./TimeSpan";
export class Stopwatch {
private _elapsed: number[] = [0, 0];
private _start?: number[];
public static startNew(): Stopwatch {
let result = new Stopwatch();
result.start();
return result;
}
public start(): void {
if (this._start !== undefined) {
throw new Error("The stopwatch is already started.");
}
this._start = process.hrtime();
}
public elapsed(): TimeSpan {
let result = { seconds: this._elapsed[0], nanos: this._elapsed[1] };
if (this._start !== undefined) {
let stop = process.hrtime();
result.seconds += stop[0] - this._start[0];
if (stop[0] === this._start[0]) {
result.nanos += stop[1] - this._start[1];
} else {
result.nanos += TimeSpan.NANOS_PER_SECOND - this._start[1] + stop[1];
}
}
while (result.nanos > TimeSpan.NANOS_PER_SECOND) {
result.seconds++;
result.nanos -= TimeSpan.NANOS_PER_SECOND;
}
return new TimeSpan(result.seconds, result.nanos);
}
public elapsedMillis(): number {
return this.elapsed().totalMilliseconds;
}
}