2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 package org
.apache
.hadoop
.hbase
.util
;
21 import org
.apache
.yetus
.audience
.InterfaceAudience
;
24 * Instead of calculate a whole time average, this class focus on the last N.
25 * The last N is stored in a circle array.
27 @InterfaceAudience.Private
28 public class WindowMovingAverage
extends MovingAverage
{
29 protected final static int DEFAULT_SIZE
= 5;
31 // The last n statistics.
32 protected long[] lastN
;
33 // The index of the most recent statistics.
34 protected int mostRecent
;
35 // If it travels a round.
36 protected boolean oneRound
;
38 public WindowMovingAverage(String label
) {
39 this(label
, DEFAULT_SIZE
);
42 public WindowMovingAverage(String label
, int size
) {
44 this.lastN
= new long[size
<= 0 ? DEFAULT_SIZE
: size
];
46 this.oneRound
= false;
50 protected void updateMostRecentTime(long elapsed
) {
51 int index
= moveForwardMostRecentPosistion();
52 lastN
[index
] = elapsed
;
56 public double getAverageTime() {
57 return enoughStatistics() ?
58 (double) sum(getNumberOfStatistics()) / getNumberOfStatistics() :
59 (double) sum(getMostRecentPosistion() + 1) / (getMostRecentPosistion() + 1);
63 * Check if there are enough statistics.
64 * @return true if lastN is full
66 protected boolean enoughStatistics() {
71 * @return number of statistics
73 protected int getNumberOfStatistics() {
78 * Get statistics at index.
79 * @param index index of bar
82 protected long getStatisticsAtIndex(int index
) {
83 if (index
< 0 || index
>= getNumberOfStatistics()) {
84 // This case should not happen, but a prudent check.
85 throw new IndexOutOfBoundsException();
91 * @return index of most recent
93 protected int getMostRecentPosistion() {
98 * Move forward the most recent index.
99 * @return the most recent index
101 protected int moveForwardMostRecentPosistion() {
102 int index
= ++mostRecent
;
103 if (!oneRound
&& index
== getNumberOfStatistics()) {
104 // Back to the head of the lastN, from now on will
105 // start to evict oldest value.
108 mostRecent
= index
% getNumberOfStatistics();
112 private long sum(int bound
) {
114 for (int i
= 0; i
< bound
; i
++) {
115 sum
+= getStatisticsAtIndex(i
);