001/*
002 * Copyright 2010-2015 Institut Pasteur.
003 * 
004 * This file is part of Icy.
005 * 
006 * Icy is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 * 
011 * Icy is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 * GNU General Public License for more details.
015 * 
016 * You should have received a copy of the GNU General Public License
017 * along with Icy. If not, see <http://www.gnu.org/licenses/>.
018 */
019package icy.math;
020
021/**
022 * Uses this class to maintain and calculate a rate.
023 * 
024 * @author stephane
025 */
026public class RateMeter
027{
028    private double lastCnt;
029    private double rate;
030    private double rateCnt;
031    private double lastRateCnt;
032
033    public RateMeter()
034    {
035        super();
036
037        reset();
038    }
039
040    /**
041     * Reset counter
042     */
043    public void reset()
044    {
045        lastCnt = System.nanoTime();
046        rate = 0;
047        rateCnt = 0;
048        lastRateCnt = 0;
049    }
050
051    /**
052     * Update rate from delta<br>
053     * Return current rate
054     */
055    public double updateFromDelta(double delta)
056    {
057        return updateFromTotal(rateCnt + delta);
058    }
059
060    /**
061     * Update rate from total<br>
062     * Return current rate
063     */
064    public double updateFromTotal(double total)
065    {
066        final double curCnt = System.nanoTime();
067        final double difCnt = curCnt - lastCnt;
068
069        rateCnt = total;
070
071        if (difCnt > 1000000000d)
072        {
073            lastCnt = curCnt;
074            rate = rateCnt - lastRateCnt;
075            rate *= 1000000000d;
076            rate /= difCnt;
077            lastRateCnt = rateCnt;
078        }
079
080        return rate;
081    }
082
083    /**
084     * @return rate
085     */
086    public double getRate()
087    {
088        return rate;
089    }
090}