Stopwatch in Java Using System. In the Stopwatch1 two methods to start and stop the stopwatch, start() initializes the stopWatchStartTime with the current nanoseconds using System. nanoTime() and set the value of stopWatchRunning (checks if the stopwatch is running) as true .
A Timer in Java is a process that enables threads to schedule tasks for later execution. Scheduling is done by keeping a specific process in the queue such that when the execution time comes, the processor can suspend other processes and run the task.
Method SummaryGet the name of the currently running task, if any. Get the ID of this StopWatch , as specified on construction. Get the last task as a StopWatch. TaskInfo object.
You'll find one in
http://commons.apache.org/lang/
It's called
org.apache.commons.lang.time.StopWatch
But it roughly does the same as yours. If you're in for more precision, use
System.nanoTime()
See also this question here:
Time measuring overhead in Java
Use Guava's Stopwatch
class.
An object that measures elapsed time in nanoseconds. It is useful to measure elapsed time using this class instead of direct calls to
System.nanoTime()
for a few reasons:
- An alternate time source can be substituted, for testing or performance reasons.
- As documented by nanoTime, the value returned has no absolute meaning, and can only be interpreted as relative to another timestamp returned by nanoTime at a different time. Stopwatch is a more effective abstraction because it exposes only these relative values, not the absolute ones.
Stopwatch stopwatch = Stopwatch.createStarted();
doSomething();
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
Now you can try something like:
Instant starts = Instant.now();
Thread.sleep(10);
Instant ends = Instant.now();
System.out.println(Duration.between(starts, ends));
Output is in ISO 8601.
Spring provides an elegant org.springframework.util.StopWatch
class (spring-core
module).
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// Do something
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeMillis());
Use System.currentTimeMillis()
to get the start time and the end time and calculate the difference.
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
More info at this tutorial
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With