BenchmarkResults.java revision 5f76e1fa85f5c189d57860b0b5b02cace139204b
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 getStats() {
32        final Bundle stats = new Bundle();
33        stats.putDouble("Mean (ms)", mean());
34        stats.putDouble("Median (ms)", median());
35        stats.putDouble("Sigma (ms)", standardDeviation());
36        return stats;
37    }
38
39    public ArrayList<Long> getAllDurations() {
40        return mResults;
41    }
42
43    private double mean() {
44        final int size = mResults.size();
45        long sum = 0;
46        for (int i = 0; i < size; ++i) {
47            sum += mResults.get(i);
48        }
49        return (double) sum / size;
50    }
51
52    private double median() {
53        final int size = mResults.size();
54        if (size == 0) {
55            return 0f;
56        }
57        Collections.sort(mResults);
58        final int idx = size / 2;
59        return size % 2 == 0
60                ? (double) (mResults.get(idx) + mResults.get(idx - 1)) / 2
61                : mResults.get(idx);
62    }
63
64    private double standardDeviation() {
65        final int size = mResults.size();
66        if (size == 0) {
67            return 0f;
68        }
69        final double mean = mean();
70        double sd = 0;
71        for (int i = 0; i < size; ++i) {
72            double diff = mResults.get(i) - mean;
73            sd += diff * diff;
74        }
75        return Math.sqrt(sd / size);
76    }
77}
78