1 /* 2 * Copyright (C) 2022 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 package com.android.layoutlib.bridge.intensive.util.perf; 18 19 import android.annotation.NonNull; 20 import android.util.LongArray; 21 22 import java.util.Arrays; 23 import java.util.function.LongConsumer; 24 25 /** 26 * Class that collect a series of longs and produces the median, min and max values. 27 */ 28 public class LongStatsCollector implements LongConsumer { 29 private final LongArray mAllValues; 30 private long mMin = Long.MAX_VALUE; 31 private long mMax = Long.MIN_VALUE; LongStatsCollector(int estimatedRuns)32 public LongStatsCollector(int estimatedRuns) { 33 mAllValues = new LongArray(estimatedRuns); 34 } 35 size()36 public int size() { 37 return mAllValues.size(); 38 } 39 40 @NonNull getStats()41 public Stats getStats() { 42 if (mAllValues.size() == 0) { 43 throw new IndexOutOfBoundsException("No data"); 44 } 45 46 double median; 47 int size = mAllValues.size(); 48 long[] buffer = new long[size]; 49 for (int i = 0; i < size; i++) { 50 buffer[i] = mAllValues.get(i); 51 } 52 53 Arrays.sort(buffer); 54 55 int midPoint = size / 2; 56 median = (size % 2 == 0) ? (buffer[midPoint - 1] + buffer[midPoint]) / 2 : buffer[midPoint]; 57 58 return new Stats(mAllValues.size(), mMin, mMax, median); 59 } 60 61 @Override accept(long value)62 public void accept(long value) { 63 mMin = Math.min(mMin, value); 64 mMax = Math.max(mMax, value); 65 mAllValues.add(value); 66 } 67 68 public static class Stats { 69 private final int mSamples; 70 private final long mMin; 71 private final long mMax; 72 private final double mMedian; 73 Stats(int samples, long min, long max, double median)74 private Stats(int samples, long min, long max, double median) { 75 mSamples = samples; 76 mMin = min; 77 mMax = max; 78 mMedian = median; 79 } 80 getSampleCount()81 public int getSampleCount() { 82 return mSamples; 83 } 84 getMin()85 public long getMin() { 86 return mMin; 87 } 88 getMax()89 public long getMax() { 90 return mMax; 91 } 92 getMedian()93 public double getMedian() { 94 return mMedian; 95 } 96 } 97 } 98