Class Stopwatch

 1  
 2 /*
 3  * Copyright (c) 2016 Vivid Solutions.
 4  *
 5  * All rights reserved. This program and the accompanying materials
 6  * are made available under the terms of the Eclipse Public License 2.0
 7  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 8  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 9  * and the Eclipse Distribution License is available at
10  *
11  * http://www.eclipse.org/org/documents/edl-v10.php.
12  */
13 package org.locationtech.jts.util;
14  
15 /**
16  * Implements a timer function which can compute
17  * elapsed time as well as split times.
18  *
19  * @version 1.7
20  */
21 public class Stopwatch {
22  
23   private long startTimestamp;
24   private long totalTime = 0;
25   private boolean isRunning = false;
26  
27   public Stopwatch()
28   {
29     start();
30   }
31  
32   public void start()
33   {
34     if (isRunning) return;
35     startTimestamp = System.currentTimeMillis();
36     isRunning = true;
37   }
38  
39   public long stop()
40   {
41     if (isRunning) {
42       updateTotalTime();
43       isRunning = false;
44     }
45     return totalTime;
46   }
47  
48   public void reset()
49   {
50     totalTime = 0;
51     startTimestamp = System.currentTimeMillis();
52   }
53  
54   public long split()
55   {
56     if (isRunning)
57       updateTotalTime();
58     return totalTime;
59   }
60  
61   private void updateTotalTime()
62   {
63     long endTimestamp = System.currentTimeMillis();
64     long elapsedTime = endTimestamp - startTimestamp;
65     startTimestamp = endTimestamp;
66     totalTime += elapsedTime;
67   }
68  
69   public long getTime()
70   {
71     updateTotalTime();
72     return totalTime;
73   }
74  
75   public String getTimeString()
76   {
77     long totalTime = getTime();
78     return getTimeString(totalTime);
79   }
80  
81   public static String getTimeString(long timeMillis) {
82     String totalTimeStr = timeMillis < 10000 
83         ? timeMillis + " ms" 
84         : (double) timeMillis / 1000.0 + " s";
85     return totalTimeStr;
86   }
87 }
88