1 /* 2 * Copyright (C) 2016 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.server.notification; 18 19 20 /** 21 * Exponentially weighted moving average estimator for event rate. 22 * 23 * {@hide} 24 */ 25 class RateEstimator { 26 private static final double RATE_ALPHA = 0.7; 27 private static final double MINIMUM_DT = 0.0005; 28 29 private Long mLastEventTime; 30 private double mInterarrivalTime; 31 RateEstimator()32 public RateEstimator() { 33 // assume something generous if we have no information 34 mInterarrivalTime = 1000.0; 35 } 36 37 /** Update the estimate to account for an event that just happened. */ update(long now)38 public void update(long now) { 39 if (mLastEventTime != null) { 40 // Calculate the new inter-arrival time based on last event time. 41 mInterarrivalTime = getInterarrivalEstimate(now); 42 } 43 mLastEventTime = now; 44 } 45 46 /** @return the estimated rate if there were a new event right now. */ getRate(long now)47 public float getRate(long now) { 48 if (mLastEventTime == null) { 49 return 0f; 50 } 51 return (float) (1.0 / getInterarrivalEstimate(now)); 52 } 53 54 /** @return the average inter-arrival time if there were a new event right now. */ getInterarrivalEstimate(long now)55 private double getInterarrivalEstimate(long now) { 56 double dt = ((double) (now - mLastEventTime)) / 1000.0; 57 dt = Math.max(dt, MINIMUM_DT); 58 // a*iat_old + (1-a)*(t_now-t_last) 59 return (RATE_ALPHA * mInterarrivalTime + (1.0 - RATE_ALPHA) * dt); 60 } 61 } 62