UNPKG

1.85 kBJavaScriptView Raw
1'use strict';
2
3function InteractivePerf() {
4 this._recording = false;
5 this._startTime = window.performance.now();
6 this._results = [];
7}
8
9InteractivePerf.prototype.toggleRecording = function() {
10 if (this._recording) {
11 this.stopRecording();
12 } else {
13 this.startRecording();
14 }
15}
16
17InteractivePerf.prototype.startRecording = function() {
18 this._recording = true;
19}
20
21InteractivePerf.prototype.stopRecording = function() {
22 this._recording = false;
23 if (!this._results.length) {
24 console.log('Finished recording with no results');
25 } else {
26 var averageDuration = this._results.reduce(function(sum, value) {
27 return sum + value;
28 }, 0) / this._results.length;
29 console.log('Average duration: ' + InteractivePerf.formatDuration(averageDuration));
30 console.log('Average FPS: ' + (1000 / averageDuration).toFixed(2));
31 console.log('Number of samples: ' + this._results.length);
32 }
33 this._clearResults();
34}
35
36InteractivePerf.prototype.begin = function() {
37 this._startTime = window.performance.now();
38}
39
40InteractivePerf.prototype.end = function(message) {
41 var endTime = window.performance.now();
42 var duration = endTime - this._startTime;
43
44 if (message) {
45 console.log(message + ': ' + InteractivePerf.formatDuration(duration));
46 } else if (!this._recording) {
47 console.debug('Unrecorded: ' + InteractivePerf.formatDuration(duration));
48 }
49 if (this._recording) {
50 this._results.push(duration);
51 }
52}
53
54InteractivePerf.formatDuration = function(duration) {
55 if (duration < 1000) {
56 return duration + ' ms';
57 } else {
58 return (duration / 1000).toFixed(2) + ' seconds';
59 }
60}
61
62InteractivePerf.prototype._clearResults = function() {
63 this._recording = false;
64 this._results = [];
65}