• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <input/LatencyStatistics.h>
18 
19 #include <android-base/chrono_utils.h>
20 
21 #include <cmath>
22 #include <limits>
23 
24 namespace android {
25 
LatencyStatistics(std::chrono::seconds period)26 LatencyStatistics::LatencyStatistics(std::chrono::seconds period) : mReportPeriod(period) {
27     reset();
28 }
29 
30 /**
31  * Add a raw value to the statistics
32  */
addValue(float value)33 void LatencyStatistics::addValue(float value) {
34     if (value < mMin) {
35         mMin = value;
36     }
37     if (value > mMax) {
38         mMax = value;
39     }
40     mSum += value;
41     mSum2 += value * value;
42     mCount++;
43 }
44 
45 /**
46  * Get the mean. Should not be called if no samples have been added.
47  */
getMean()48 float LatencyStatistics::getMean() {
49     return mSum / mCount;
50 }
51 
52 /**
53  * Get the standard deviation. Should not be called if no samples have been added.
54  */
getStDev()55 float LatencyStatistics::getStDev() {
56     float mean = getMean();
57     return sqrt(mSum2 / mCount - mean * mean);
58 }
59 
getMin()60 float LatencyStatistics::getMin() {
61     return mMin;
62 }
63 
getMax()64 float LatencyStatistics::getMax() {
65     return mMax;
66 }
67 
getCount()68 size_t LatencyStatistics::getCount() {
69     return mCount;
70 }
71 
72 /**
73  * Reset internal state. The variable 'when' is the time when the data collection started.
74  * Call this to start a new data collection window.
75  */
reset()76 void LatencyStatistics::reset() {
77     mMax = std::numeric_limits<float>::lowest();
78     mMin = std::numeric_limits<float>::max();
79     mSum = 0;
80     mSum2 = 0;
81     mCount = 0;
82     mLastReportTime = std::chrono::steady_clock::now();
83 }
84 
shouldReport()85 bool LatencyStatistics::shouldReport() {
86     std::chrono::duration timeSinceReport = std::chrono::steady_clock::now() - mLastReportTime;
87     return mCount != 0 && timeSinceReport >= mReportPeriod;
88 }
89 
90 } // namespace android
91