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, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.wake.metrics; 020 021import java.util.concurrent.atomic.AtomicLong; 022import java.util.concurrent.atomic.AtomicLongArray; 023 024/** 025 * An {@link Histogram} that implements uniform binning of numbers ({@code >=0}). 026 */ 027public class UniformHistogram implements Histogram { 028 private final AtomicLong count; 029 private final AtomicLongArray values; 030 private final long binWidth; 031 private final int numBins; 032 033 /** 034 * Constructs a histogram. 035 * 036 * @param binWidth the width of each bin 037 * @param numBins the number of bins 038 */ 039 public UniformHistogram(final long binWidth, final int numBins) { 040 this.count = new AtomicLong(0); 041 this.values = new AtomicLongArray(numBins); 042 this.binWidth = binWidth; 043 this.numBins = numBins; 044 } 045 046 /** 047 * Updates the value. 048 * 049 * @param value 050 */ 051 @Override 052 public void update(final long value) { 053 count.incrementAndGet(); 054 int index = (int) (value / binWidth); 055 if (index >= numBins) { 056 index = numBins - 1; 057 } 058 values.incrementAndGet(index); 059 } 060 061 /** 062 * Returns the number of recorded values. 063 * 064 * @return the number of recorded values 065 */ 066 @Override 067 public long getCount() { 068 return count.get(); 069 } 070 071 /** 072 * Returns the value of the index. 073 * 074 * @param index the index 075 * @return the value of the index 076 */ 077 @Override 078 public long getValue(final int index) { 079 return values.get(index); 080 } 081 082 /** 083 * Returns the number of bins. 084 * 085 * @return the number of bins 086 */ 087 @Override 088 public int getNumBins() { 089 return numBins; 090 } 091}