blob: b3d5f1f3f6d85398a6e353291731ccbb8fd93550 [file] [log] [blame]
Sanna Catherine de Treville Wagerd0dfe432017-06-22 15:09:38 -07001/*
2 * Copyright (C) 2017 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
18#define LOG_TAG "PerformanceAnalysis"
19// #define LOG_NDEBUG 0
20
21#include <algorithm>
22#include <climits>
23#include <deque>
24#include <fstream>
25// #include <inttypes.h>
26#include <iostream>
27#include <math.h>
28#include <numeric>
29#include <vector>
30#include <stdarg.h>
31#include <stdint.h>
32#include <stdio.h>
33#include <string.h>
34#include <sys/prctl.h>
35#include <time.h>
36#include <new>
37#include <audio_utils/roundup.h>
38#include <media/nbaio/NBLog.h>
39#include <media/nbaio/PerformanceAnalysis.h>
40// #include <utils/CallStack.h> // used to print callstack
41#include <utils/Log.h>
42#include <utils/String8.h>
43
44#include <queue>
45#include <utility>
46
47namespace android {
48
49PerformanceAnalysis::PerformanceAnalysis() : findGlitch(false) {
50 ALOGE("this value should be 4: %d", kPeriodMs);
51 kPeriodMsCPU = static_cast<int>(PerformanceAnalysis::kPeriodMs * kRatio);
52}
53
54static int widthOf(int x) {
55 int width = 0;
56 while (x > 0) {
57 ++width;
58 x /= 10;
59 }
60 return width;
61}
62
63// WIP: uploading this half-written function to get code review on
64// cleanup and new file creation.
65/*
66static std::vector<std::pair<int, int>> outlierIntervals(
67 const std::deque<std::pair<int, short_histogram>> &shortHists) {
68 // TODO: need the timestamps
69 if (shortHists.size() < 1) {
70 return;
71 }
72 // count number of outliers in histogram
73 // TODO: need the alertIfGlitch analysis on the time series in NBLog::reader
74 // to find all the glitches
75 const std::vector<int> glitchCount = std::vector<int>(shortHists.size());
76 // Total ms elapsed in each shortHist
77 const std::vector<int> timeElapsedMs = std::vector<int>(shortHists.size());
78 int i = 0;
79 for (const auto &shortHist: shortHists) {
80 for (const auto &bin: shortHist) {
81 timeElapsedMs.at(i) += bin->first * bin->second;
82 if (bin->first >= kGlitchThreshMs) {
83 glitchCount.at(i) += bin->second;
84 }
85 }
86 i++;
87 }
88 // seconds between glitches and corresponding timestamp
89 const std::vector<std::pair<double, int>> glitchFreeIntervalsSec;
90 // Sec since last glitch. nonzero if the duration spans many shortHists
91 double glitchFreeSec = 0;
92 for (int i = 0; i < kGlitchCount.size(); i++) {
93 if (kGlitchCount.at(i) == 0) {
94 glitchFreeSec += static_cast<double>timeElapsedMs.at(i) / kMsPerSec;
95 }
96 else {
97 // average time between glitches in this interval
98 const double kInterval = static_cast<double>(timeElapsedMs.at(i)) / kGlitchCount.at(i);
99 for (int j = 0; j < kGlitchCount.at(i); j++) {
100 kIntervals.emplace_front(kInterval);
101 }
102 }
103 }
104 return;
105}*/
106
107// TODO: implement peak detector
108/*
109static void peakDetector() {
110 return;
111} */
112
113// TODO put this function in separate file. Make it return a std::string instead of modifying body
114// TODO create a subclass of Reader for this and related work
115// FIXME: as can be seen when printing the values, the outlier timestamps typically occur
116// in the first histogram 35 to 38 indices from the end (most often 35).
117// TODO: build histogram buckets earlier and discard timestamps to save memory
118// TODO consider changing all ints to uint32_t or uint64_t
119void PerformanceAnalysis::reportPerformance(String8 *body,
120 const std::deque<std::pair
121 <int, short_histogram>> &shortHists,
122 int maxHeight) {
123 if (shortHists.size() < 1) {
124 return;
125 }
126 // this is temporary code, which only prints out one histogram
127 // of all data stored in buffer. The data is not erased, only overwritten.
128 // TODO: more elaborate data analysis
129 std::map<int, int> buckets;
130 for (const auto &shortHist: shortHists) {
131 for (const auto &countPair : shortHist.second) {
132 buckets[countPair.first] += countPair.second;
133 }
134 }
135
136 // underscores and spaces length corresponds to maximum width of histogram
137 static const int kLen = 40;
138 std::string underscores(kLen, '_');
139 std::string spaces(kLen, ' ');
140
141 auto it = buckets.begin();
142 int maxDelta = it->first;
143 int maxCount = it->second;
144 // Compute maximum values
145 while (++it != buckets.end()) {
146 if (it->first > maxDelta) {
147 maxDelta = it->first;
148 }
149 if (it->second > maxCount) {
150 maxCount = it->second;
151 }
152 }
153 int height = log2(maxCount) + 1; // maxCount > 0, safe to call log2
154 const int leftPadding = widthOf(1 << height);
155 const int colWidth = std::max(std::max(widthOf(maxDelta) + 1, 3), leftPadding + 2);
156 int scalingFactor = 1;
157 // scale data if it exceeds maximum height
158 if (height > maxHeight) {
159 scalingFactor = (height + maxHeight) / maxHeight;
160 height /= scalingFactor;
161 }
162 body->appendFormat("\n%*s", leftPadding + 11, "Occurrences");
163 // write histogram label line with bucket values
164 body->appendFormat("\n%s", " ");
165 body->appendFormat("%*s", leftPadding, " ");
166 for (auto const &x : buckets) {
167 body->appendFormat("%*d", colWidth, x.second);
168 }
169 // write histogram ascii art
170 body->appendFormat("\n%s", " ");
171 for (int row = height * scalingFactor; row >= 0; row -= scalingFactor) {
172 const int value = 1 << row;
173 body->appendFormat("%.*s", leftPadding, spaces.c_str());
174 for (auto const &x : buckets) {
175 body->appendFormat("%.*s%s", colWidth - 1, spaces.c_str(), x.second < value ? " " : "|");
176 }
177 body->appendFormat("\n%s", " ");
178 }
179 // print x-axis
180 const int columns = static_cast<int>(buckets.size());
181 body->appendFormat("%*c", leftPadding, ' ');
182 body->appendFormat("%.*s", (columns + 1) * colWidth, underscores.c_str());
183 body->appendFormat("\n%s", " ");
184
185 // write footer with bucket labels
186 body->appendFormat("%*s", leftPadding, " ");
187 for (auto const &x : buckets) {
188 body->appendFormat("%*d", colWidth, x.first);
189 }
190 body->appendFormat("%.*s%s", colWidth, spaces.c_str(), "ms\n");
191
192}
193
194
195// Produces a log warning if the timing of recent buffer periods caused a glitch
196// Computes sum of running window of three buffer periods
197// Checks whether the buffer periods leave enough CPU time for the next one
198// e.g. if a buffer period is expected to be 4 ms and a buffer requires 3 ms of CPU time,
199// here are some glitch cases:
200// 4 + 4 + 6 ; 5 + 4 + 5; 2 + 2 + 10
201// TODO: develop this code to track changes in histogram distribution in addition
202// to / instead of glitches.
203void PerformanceAnalysis::alertIfGlitch(const std::vector<int64_t> &samples) {
204 std::deque<int> periods(kNumBuff, kPeriodMs);
205 for (size_t i = 2; i < samples.size(); ++i) { // skip first time entry
206 periods.push_front(deltaMs(samples[i - 1], samples[i]));
207 periods.pop_back();
208 // TODO: check that all glitch cases are covered
209 if (std::accumulate(periods.begin(), periods.end(), 0) > kNumBuff * kPeriodMs +
210 kPeriodMs - kPeriodMsCPU) {
211 ALOGW("A glitch occurred");
212 periods.assign(kNumBuff, kPeriodMs);
213 }
214 }
215 return;
216}
217
218bool PerformanceAnalysis::isFindGlitch() const
219{
220 return findGlitch;
221}
222
223void PerformanceAnalysis::setFindGlitch(bool s)
224{
225 findGlitch = s;
226}
227//TODO: ask Andy where to keep '= 4'
228const int PerformanceAnalysis::kPeriodMs; // = 4;
229
230} // namespace android