-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.java
75 lines (57 loc) · 1.81 KB
/
Timer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Copyright (c) 2016, Carnegie Mellon University. All Rights Reserved.
*/
import java.math.BigDecimal;
/**
* A simple timer.
*/
public class Timer {
// Class variables
private long timeStart=0;
private long timeStop=0;
private boolean isRunning=false;
private boolean hasRun=false;
private static final BigDecimal MILLION = new BigDecimal ("1000000");
/**
* Start the timer.
* @throws IllegalStateException If the timer is started again while running.
*/
public void start () {
if (this.isRunning)
throw new IllegalStateException (
"The timer must be stopped before it can be started again.");
this.timeStart = System.nanoTime();
this.isRunning = true;
}
/**
* Stop the timer.
* @throws IllegalStateException If the timer is stopped before it is started.
*/
public void stop () {
if (! this.isRunning)
throw new IllegalStateException (
"The timer must be started before it can be stopped.");
this.timeStop = System.nanoTime();
this.isRunning = false;
this.hasRun = true;
}
/**
* Converts a timing result to a string.
* @throws IllegalStateException The timer hasn't been run or is running now.
*/
@Override public String toString() {
if (! this.hasRun)
throw new IllegalStateException(
"The timer cannot be read because it has not been run.");
else
if (this.isRunning)
throw new IllegalStateException(
"The timer cannot be read while it is running.");
BigDecimal value = new BigDecimal(this.timeStop - this.timeStart);
value = value.divide (MILLION, 3, BigDecimal.ROUND_HALF_EVEN);
StringBuilder result = new StringBuilder();
result.append(value);
result.append(" ms");
return result.toString();
}
}