stopwatch.ts 1.2 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import { globals } from 'vs/base/common/platform';

B
Benjamin Pasero 已提交
9
const hasPerformanceNow = (globals.performance && typeof globals.performance.now === 'function');
E
Erich Gamma 已提交
10 11 12

export class StopWatch {

13
	private _highResolution: boolean;
E
Erich Gamma 已提交
14 15 16
	private _startTime: number;
	private _stopTime: number;

J
Johannes Rieken 已提交
17
	public static create(highResolution: boolean = true): StopWatch {
18
		return new StopWatch(highResolution);
E
Erich Gamma 已提交
19 20
	}

21 22 23
	constructor(highResolution: boolean) {
		this._highResolution = hasPerformanceNow && highResolution;
		this._startTime = this._now();
E
Erich Gamma 已提交
24 25 26 27
		this._stopTime = -1;
	}

	public stop(): void {
28
		this._stopTime = this._now();
E
Erich Gamma 已提交
29 30 31 32 33 34
	}

	public elapsed(): number {
		if (this._stopTime !== -1) {
			return this._stopTime - this._startTime;
		}
35 36 37 38 39
		return this._now() - this._startTime;
	}

	private _now(): number {
		return this._highResolution ? globals.performance.now() : new Date().getTime();
E
Erich Gamma 已提交
40 41
	}
}