001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import org.apache.yetus.audience.InterfaceAudience; 021 022/** 023 * Different from SMA {@link SimpleMovingAverage}, WeightedMovingAverage gives each data different 024 * weight. And it is based on {@link WindowMovingAverage}, such that it only focus on the last N. 025 */ 026@InterfaceAudience.Private 027public class WeightedMovingAverage<T> extends WindowMovingAverage<T> { 028 private int[] coefficient; 029 private int denominator; 030 031 public WeightedMovingAverage(String label) { 032 this(label, DEFAULT_SIZE); 033 } 034 035 public WeightedMovingAverage(String label, int size) { 036 super(label, size); 037 int length = getNumberOfStatistics(); 038 denominator = length * (length + 1) / 2; 039 coefficient = new int[length]; 040 // E.g. default size is 5, coefficient should be [1, 2, 3, 4, 5] 041 for (int i = 0; i < length; i++) { 042 coefficient[i] = i + 1; 043 } 044 } 045 046 @Override 047 public double getAverageTime() { 048 if (!enoughStatistics()) { 049 return super.getAverageTime(); 050 } 051 // only we get enough statistics, then start WMA. 052 double average = 0.0; 053 int coIndex = 0; 054 int length = getNumberOfStatistics(); 055 // tmIndex, it points to the oldest data. 056 for (int tmIndex = (getMostRecentPosition() + 1) % length; coIndex 057 < length; coIndex++, tmIndex = ++tmIndex % length) { 058 // start the multiplication from oldest to newest 059 average += coefficient[coIndex] * getStatisticsAtIndex(tmIndex); 060 } 061 return average / denominator; 062 } 063}