1/*
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        Collections.sort(mResults);
64        final int idx = size / 2;
65        return size % 2 == 0
66                ? (double) (mResults.get(idx) + mResults.get(idx - 1)) / 2
67                : mResults.get(idx);
68    }
69
70    private double standardDeviation() {
71        final int size = mResults.size();
72        if (size == 0) {
73            return 0f;
74        }
75        final double mean = mean();
76        double sd = 0;
77        for (int i = 0; i < size; ++i) {
78            double diff = mResults.get(i) - mean;
79            sd += diff * diff;
80        }
81        return Math.sqrt(sd / size);
82    }
83}
84