-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimingController.java
118 lines (103 loc) · 2.66 KB
/
TimingController.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import java.util.ArrayList;
import java.util.List;
/**
* The objects of this class are used to control timing with System time.
*
* @author Team APCSA 2019
* @author Yijie Gui
* @since 2019-05-23 16:41
*/
@SuppressWarnings("WeakerAccess")
public class TimingController
{
/** List of timing events */
private List<TimingEvent> events = new ArrayList<>();
/**
* @return Is running or not.
*/
public boolean isRunning()
{
return events.size() != 0 && events.get(events.size() - 1).start;
}
/**
* Start the timer.
*/
public void start()
{
start(0);
}
/**
* Start the timer.
*
* @param offset Offset time.
*/
public void start(int offset)
{
if (isRunning())
{
throw new RuntimeException("You can't start an already started timer.");
}
events.add(new TimingEvent(System.currentTimeMillis() + offset, true));
}
/**
* Stop the timer.
*/
public void stop()
{
if (!isRunning())
{
throw new RuntimeException("You can't stop an already stopped timer.");
}
events.add(new TimingEvent(System.currentTimeMillis(), false));
}
/**
* Reset the timer.
*/
public void reset()
{
events = new ArrayList<>();
}
/**
* Calculate the total duration.
*
* @return The total duration (ignoring pauses)
*/
public int getTotalDuration()
{
long total = 0;
// Count total
for (TimingEvent event : events)
{
total += event.timestamp * (event.start ? 1 : -1);
}
// If the last one is not STOP, assume it stops now.
if (isRunning())
{
total -= System.currentTimeMillis();
}
// Returns negative total because total = end - start
return (int) -total;
}
/**
* A timing event records one change in the timer. For example, if
* you started the timer, that's a timing event.
*/
private class TimingEvent
{
/** Timestamp of this event. */
private final long timestamp;
/** Is this a start even or an end event */
private final boolean start;
/**
* Construct a timing event
*
* @param timestamp Timestamp
* @param start True = start, False = end
*/
private TimingEvent(long timestamp, boolean start)
{
this.timestamp = timestamp;
this.start = start;
}
}
}