001/*
002 * @(#)Timer.java       1.0 June 2010
003 *
004 * Copyright (c) 2010 Peter Troshin
005 *
006 *        BioJava development code
007 *
008 * This code may be freely distributed and modified under the
009 * terms of the GNU Lesser General Public Licence.  This should
010 * be distributed with the code.  If you do not have a copy,
011 * see:
012 *
013 *      http://www.gnu.org/copyleft/lesser.html
014 *
015 * Copyright for this code is held jointly by the individual
016 * authors.  These should be listed in @author doc comments.
017 *
018 * For more information on the BioJava project and its aims,
019 * or to join the biojava-l mailing list, visit the home page
020 * at:
021 *
022 *      http://www.biojava.org/
023 *
024 */
025package org.biojava.nbio.ronn;
026
027import java.util.concurrent.TimeUnit;
028
029/**
030 * A simple timer, calculates the time interval between two events. Keeps two
031 * counters, one for long time intervals, to measure time between the start and
032 * end of the application for instance, and another for short events, to measure
033 * how long it took to reach a next block of code.
034 *
035 * @author Peter Troshin
036 * @version 1.0
037 * @since 3.0.2
038 */
039public class Timer {
040
041        private long checkPoint;
042        private final long startTime;
043        private TimeUnit reportTimeUnit;
044
045        public Timer() {
046        startTime = System.nanoTime();
047        checkPoint = startTime;
048        // set default time unit for reporting
049        reportTimeUnit = TimeUnit.SECONDS;
050        }
051
052        public Timer(final TimeUnit reportIn) {
053        this();
054        reportTimeUnit = reportIn;
055        }
056
057        public void checkPoint() {
058        checkPoint = System.nanoTime();
059        }
060
061        long getStepTime(final TimeUnit tunit) {
062        final long duration = tunit.convert(System.nanoTime() - checkPoint,
063                TimeUnit.NANOSECONDS);
064        checkPoint();
065        return duration;
066        }
067
068        long getStepTime() {
069        return getStepTime(reportTimeUnit);
070        }
071
072        long getTotalTime() {
073        return getTotalTime(reportTimeUnit);
074        }
075
076        long getTotalTime(final TimeUnit tunit) {
077        return tunit.convert(System.nanoTime() - startTime,
078                TimeUnit.NANOSECONDS);
079        }
080}