1// Copyright (C) 2024 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import m from 'mithril'; 16 17// The interface that every container (e.g. Track Panels) that exposes granular 18// per-container masurements implements to be perf-stats-aware. 19export interface PerfStatsContainer { 20 setPerfStatsEnabled(enable: boolean): void; 21 renderPerfStats(): m.Children; 22} 23 24// Stores statistics about samples, and keeps a fixed size buffer of most recent 25// samples. 26export class PerfStats { 27 private _count = 0; 28 private _mean = 0; 29 private _lastValue = 0; 30 private _ptr = 0; 31 32 private buffer: number[] = []; 33 34 constructor(private _maxBufferSize = 10) {} 35 36 addValue(value: number) { 37 this._lastValue = value; 38 if (this.buffer.length >= this._maxBufferSize) { 39 this.buffer[this._ptr++] = value; 40 if (this._ptr >= this.buffer.length) { 41 this._ptr -= this.buffer.length; 42 } 43 } else { 44 this.buffer.push(value); 45 } 46 47 this._mean = (this._mean * this._count + value) / (this._count + 1); 48 this._count++; 49 } 50 51 get mean() { 52 return this._mean; 53 } 54 get count() { 55 return this._count; 56 } 57 get bufferMean() { 58 return this.buffer.reduce((sum, v) => sum + v, 0) / this.buffer.length; 59 } 60 get bufferSize() { 61 return this.buffer.length; 62 } 63 get maxBufferSize() { 64 return this._maxBufferSize; 65 } 66 get last() { 67 return this._lastValue; 68 } 69} 70 71// Returns a summary string representation of a RunningStatistics object. 72export function runningStatStr(stat: PerfStats) { 73 return ( 74 `Last: ${stat.last.toFixed(2)}ms | ` + 75 `Avg: ${stat.mean.toFixed(2)}ms | ` + 76 `Avg${stat.maxBufferSize}: ${stat.bufferMean.toFixed(2)}ms` 77 ); 78} 79