-
Notifications
You must be signed in to change notification settings - Fork 0
/
StopWatch.java
62 lines (57 loc) · 1.46 KB
/
StopWatch.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
/**
* A stopwatch accumulates time when it is running. You can repeatedly start and
* stop the stopwatch. You can use a stopwatch to measure the running time of a
* program.
*/
public class StopWatch {
private long elapsedTime;
private long startTime;
private boolean isRunning;
/**
* Constructs a stopwatch that is in the stopped state and has no time
* accumulated.
*/
public StopWatch() {
reset();
}
/**
* Starts the stopwatch. Time starts accumulating now.
*/
public void start() {
if (isRunning)
return;
isRunning = true;
startTime = System.nanoTime();
}
/**
* Stops the stopwatch. Time stops accumulating and is is added to the
* elapsed time.
*/
public void stop() {
if (!isRunning)
return;
isRunning = false;
long endTime = System.nanoTime();
elapsedTime = elapsedTime + endTime - startTime;
}
/**
* Returns the total elapsed time.
*
* @return the total elapsed time
*/
public long getElapsedTime() {
if (isRunning) {
long endTime = System.nanoTime();
elapsedTime = elapsedTime + endTime - startTime;
startTime = endTime;
}
return elapsedTime;
}
/**
* Stops the watch and resets the elapsed time to 0.
*/
public void reset() {
elapsedTime = 0;
isRunning = false;
}
}