Stopwatch.java
package edu.odu.cs.cs350;
/**
* A simple utility class for measuring elapsed execution time.
* <p>
* The {@code Stopwatch} records the starting time when {@link #start()} is
* called, and computes elapsed time on demand using {@link #elapsedSeconds()}
* or {@link #elapsedMilliseconds()}.
* </p>
*
* <p>
* This class does not automatically stop; the stopwatch is considered to
* "stop" at the moment an elapsed time method is called. This makes it
* suitable for profiling individual operations or measuring the total
* runtime of a program segment.
* </p>
*/
public class Stopwatch {
/**
* Records the starting timestamp in nanoseconds.
*/
private long startTime;
/**
* Starts or restarts the stopwatch.
* <p>
* This method captures the current time in nanoseconds and overwrites any
* previously stored start time.
* </p>
*/
public void start() {
startTime = System.nanoTime();
}
/**
* Returns the elapsed time in seconds since the last call to {@link #start()}.
* <p>
* This method does not stop the stopwatch; it simply computes the elapsed
* difference between the current time and {@code startTime}.
* </p>
*
* @return elapsed time in seconds as a double
*/
public double elapsedSeconds() {
return (System.nanoTime() - startTime) / 1_000_000_000.0;
}
/**
* Returns the elapsed time in milliseconds since the last call to {@link #start()}.
*
* @return elapsed time in milliseconds as a long
*/
public long elapsedMilliseconds() {
return (System.nanoTime() - startTime) / 1_000_000L;
}
}