Repository navigation
Expand file tree
/
Copy pathCodeTimer.java
More file actions
36 lines (31 loc) · 1.47 KB
/
Copy pathCodeTimer.java
File metadata and controls
36 lines (31 loc) · 1.47 KB
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
public class CodeTimer {
private static long startTime;
private CodeTimer() {
// Prevent objects from being created
}
public static void start() {
startTime = System.nanoTime();
}
public static String stop() {
return stop("milliseconds");
}
public static String stop(String unit) {
long elapsedNanoseconds = System.nanoTime() - startTime;
if (unit.equalsIgnoreCase("nano") || unit.equalsIgnoreCase("ns") || unit.equalsIgnoreCase("n") ) {
return elapsedNanoseconds + " ns";
} else if (unit.equalsIgnoreCase("seconds")|| unit.equalsIgnoreCase("sec") || unit.equalsIgnoreCase("s")) {
double seconds = elapsedNanoseconds / 1_000_000_000.0;
return String.format("%.1f seconds", seconds);
} else if (unit.equalsIgnoreCase("minutes")|| unit.equalsIgnoreCase("min") || unit.equalsIgnoreCase("m")) {
double minutes = elapsedNanoseconds / 60_000_000_000.0;
return String.format("%.1f minutes", minutes);
} else if (unit.equalsIgnoreCase("milliseconds")|| unit.equalsIgnoreCase("ms") || unit.equalsIgnoreCase("milli")) {
double milliseconds = elapsedNanoseconds / 1_000_000.0;
return String.format("%.1f ms", milliseconds);
} else {
throw new IllegalArgumentException(
"Unit must be milliseconds, nano, seconds, or minutes."
);
}
}
}