View Javadoc

1   package org.e2etrace.timer;
2   
3   /*
4    * Copyright 2006 Gunther Popp
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
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.
17   */
18  
19  /**
20   * Timer Implementation with high accuracy regardless of the operating system.
21   * <p>
22   *
23   * New JDKs provide an API for measuring time intervals that works accurate on
24   * all operating systems. To be exact: It guarantees the accuracy the operating
25   * system is able to deliver. In most to all cases this should be about 1-2ms.
26   * <p>
27   *
28   * @author Gunther Popp
29   */
30  public class ExactTimer implements ITimer {
31  
32    private long duration = -1;
33    private long start = -1;
34  
35    /**
36     * Constructor. New instances can only be created by
37     * {@link DefaultTimerFactory}
38     */
39    ExactTimer() {
40  
41    }
42  
43    /** {@inheritDoc} */
44    public void start() {
45      start = System.nanoTime();
46  
47    }
48  
49    /** {@inheritDoc} */
50    public long measure() {
51      if (start > 0) {
52        duration = ((System.nanoTime()) - start) / 1000000;
53      }
54  
55      return duration;
56  
57    }
58  
59  }