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 */ 018 019package org.apache.hadoop.hbase.util; 020 021import org.apache.yetus.audience.InterfaceAudience; 022 023/** 024 * Different from SMA {@link SimpleMovingAverage}, WeightedMovingAverage gives each data different 025 * weight. And it is based on {@link WindowMovingAverage}, such that it only focus on the last N. 026 */ 027@InterfaceAudience.Private 028public class WeightedMovingAverage extends WindowMovingAverage { 029 private int[] coefficient; 030 private int denominator; 031 032 public WeightedMovingAverage(String label) { 033 this(label, DEFAULT_SIZE); 034 } 035 036 public WeightedMovingAverage(String label, int size) { 037 super(label, size); 038 int length = getNumberOfStatistics(); 039 denominator = length * (length + 1) / 2; 040 coefficient = new int[length]; 041 // E.g. default size is 5, coefficient should be [1, 2, 3, 4, 5] 042 for (int i = 0; i < length; i++) { 043 coefficient[i] = i + 1; 044 } 045 } 046 047 @Override 048 public double getAverageTime() { 049 if (!enoughStatistics()) { 050 return super.getAverageTime(); 051 } 052 // only we get enough statistics, then start WMA. 053 double average = 0.0; 054 int coIndex = 0; 055 int length = getNumberOfStatistics(); 056 // tmIndex, it points to the oldest data. 057 for (int tmIndex = (getMostRecentPosistion() + 1) % length; 058 coIndex < length; 059 coIndex++, tmIndex = (++tmIndex) % length) { 060 // start the multiplication from oldest to newest 061 average += coefficient[coIndex] * getStatisticsAtIndex(tmIndex); 062 } 063 return average / denominator; 064 } 065}