-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathStopWatch.java
57 lines (47 loc) · 1.23 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
import java.util.ArrayList;
// Saved in the d2l-java package for later use
class StopWatch {
// Record multiple running times.
private ArrayList<Double> times;
private long tik;
public StopWatch() {
times = new ArrayList<>();
start();
}
public void start() {
tik = System.nanoTime();
}
public double stop() {
times.add(nanoToSec(System.nanoTime() - tik));
return times.get(times.size() - 1);
}
public ArrayList<Double> getTimes() {
return times;
}
// Return average time
public double avg() {
return sum() / times.size();
}
// Return the sum of time
public double sum() {
double sum = 0;
for (double d : times) {
sum += d;
}
return sum;
}
// Return the accumulated times
public ArrayList<Double> cumsum() {
ArrayList<Double> cumsumList = new ArrayList<>();
double currentSum = 0;
for (Double d : times) {
currentSum += d;
cumsumList.add(currentSum);
}
return cumsumList;
}
// Convert nano seconds to seconds
private double nanoToSec(long nanosec) {
return (double) nanosec / 1E9;
}
}