-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopwatch.java
More file actions
52 lines (44 loc) · 1.41 KB
/
Stopwatch.java
File metadata and controls
52 lines (44 loc) · 1.41 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*************************************************************************
* Compilation: javac Stopwatch.java
*
*
*************************************************************************/
/**
* The <tt>Stopwatch</tt> data type is for measuring
* the time that elapses between the start and end of a
* programming task (wall-clock time).
*
* See {@link StopwatchCPU} for a version that measures CPU time.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Stopwatch {
private final long start;
/**
* Initialize a stopwatch object.
*/
public Stopwatch() {
start = System.currentTimeMillis();
}
/**
* Returns the elapsed time (in seconds) since this object was created.
*/
public double elapsedTime() {
long now = System.currentTimeMillis();
return (now - start) / 1000.0;
}
public String toTime(){
double time = elapsedTime();
String seconds = "" + (int) (time%60);
String minutes = "" + (int)((time%3600)/60);
String hours = "" + (int)(time/3600);
if (seconds.length() == 1)
seconds = "0" + seconds;
if (minutes.length() == 1)
minutes = " 0" + minutes;
if (hours.length() == 1)
hours = "0" + hours;
return "Time: " + hours + ":" + minutes + ":" + seconds;
}
}