blob: c1362dc3a6a712feb8d895ab59c880c5fd3580c0 [file] [log] [blame]
Alan Viverette3da604b2020-06-10 18:34:39 +00001/*
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 */
16package android.multiuser;
17
18import android.os.Bundle;
19
20import java.util.ArrayList;
21import java.util.Collections;
22import java.util.concurrent.TimeUnit;
23
24public class BenchmarkResults {
25 private final ArrayList<Long> mResults = new ArrayList<>();
26
27 public void addDuration(long duration) {
28 mResults.add(TimeUnit.NANOSECONDS.toMillis(duration));
29 }
30
31 public Bundle getStatsToReport() {
32 final Bundle stats = new Bundle();
33 stats.putDouble("Mean (ms)", mean());
34 return stats;
35 }
36
37 public Bundle getStatsToLog() {
38 final Bundle stats = new Bundle();
39 stats.putDouble("Mean (ms)", mean());
40 stats.putDouble("Median (ms)", median());
41 stats.putDouble("Sigma (ms)", standardDeviation());
42 return stats;
43 }
44
45 public ArrayList<Long> getAllDurations() {
46 return mResults;
47 }
48
49 private double mean() {
50 final int size = mResults.size();
51 long sum = 0;
52 for (int i = 0; i < size; ++i) {
53 sum += mResults.get(i);
54 }
55 return (double) sum / size;
56 }
57
58 private double median() {
59 final int size = mResults.size();
60 if (size == 0) {
61 return 0f;
62 }
63
64 final ArrayList<Long> resultsCopy = new ArrayList<>(mResults);
65 Collections.sort(resultsCopy);
66 final int idx = size / 2;
67 return size % 2 == 0
68 ? (double) (resultsCopy.get(idx) + resultsCopy.get(idx - 1)) / 2
69 : resultsCopy.get(idx);
70 }
71
72 private double standardDeviation() {
73 final int size = mResults.size();
74 if (size == 0) {
75 return 0f;
76 }
77 final double mean = mean();
78 double sd = 0;
79 for (int i = 0; i < size; ++i) {
80 double diff = mResults.get(i) - mean;
81 sd += diff * diff;
82 }
83 return Math.sqrt(sd / size);
84 }
85}