In order to continue with my next "Factorial and Fibonacci" posts in some Java/JVM languages; I was looking for an official Java version of the .NET Timer class "Stopwatch" (System.Diagnostics.Stopwatch), so I can measure and display the elapsed time results in the same way I had been doing it in my previous posts.
Let's show some C# code of what I meant before continuing.
using System; using System.Numerics; using System.Diagnostics; namespace CSStopwatchApp { class StopwatchApp { static void Main(string[] args) { Stopwatch timer = new Stopwatch(); timer.Start(); Fibonacci(50); timer.Stop(); Console.WriteLine("Elapsed time in ticks: {0}", timer.Elapsed.Ticks); Console.WriteLine("Elapsed time in milliseconds: {0}", timer.Elapsed.Milliseconds); Console.WriteLine("Elapsed time in seconds: {0}", timer.Elapsed.Seconds); Console.WriteLine("Elapsed time in minutes: {0}", timer.Elapsed.Minutes); Console.WriteLine("Elapsed time in hours: {0}", timer.Elapsed.Hours); Console.WriteLine("Elapsed time with format: {0}", timer.Elapsed); } private static BigInteger Fibonacci(int n) { if (n < 2) return 1; else return Fibonacci(n - 1) + Fibonacci(n - 2); } } }
And the result:
However, looks like there isn't one, instead, there are 2 methods used to measure time in Java: System.nanoTime() and System.currentTimeMillis() being the first one more precise when timing code execution.
currentTimeMillis
public static long currentTimeMillis()Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
For example, to measure how long some code takes to execute:
long startTime = System.currentTimeMillis(); // ... the code being measured ... long estimatedTime = System.currentTimeMillis() - startTime;
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
nanoTime
public static long nanoTime()Returns the current value of the most precise available system timer, in nanoseconds.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
For example, to measure how long some code takes to execute:
long startTime = System.nanoTime(); // ... the code being measured ... long estimatedTime = System.nanoTime() - startTime;
Returns:
The current value of the system timer, in nanoseconds.
So, I decided to do my own version of the Stopwatch class, not before doing some google to see if someone did it already ;) you know, code reuse FTW!
Quickly I found a basic version using System.currentTimeMillis() written by Corey Goldberg and provided with a GPL license here: http://www.goldb.org/stopwatchjava.html (thanks man!), so I took it and extended it to use System.nanoTime() instead, and implemented some other missing methods and the most important (for me) the Elapsed time formatted as "hh:mm:ss.sss" using the SimpleDateFormat class, which looks like only considers 3 milliseconds... so I added the rest (the nanoseconds part) to have: 00:00:00.0000000 (hh:mm:ss.sssssss), just like the .NET version output it. Here it is:
Stopwatch class in Java
/* * Copyright (c) 2011, Carlos Quintanilla * Special thanks to Corey Goldberg (for his StopWatch.java | Java Timer Class) * here http://www.goldb.org/stopwatchjava.html * * Stopwatch.java is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ package stopwatchapp; import java.text.SimpleDateFormat; import java.util.Calendar; /** * @author Carlos Quintanilla */ public class Stopwatch { // constants private final long nsPerTick = 100; private final long nsPerMs = 1000000; private final long nsPerSs = 1000000000; private final long nsPerMm = 60000000000L; private final long nsPerHh = 3600000000000L; private long startTime = 0; private long stopTime = 0; private boolean running = false; /** * Starts measuring elapsed time * for an interval. */ public void start() { this.startTime = System.nanoTime(); this.running = true; } /** * Stops measuring elapsed time * for an interval. */ public void stop() { this.stopTime = System.nanoTime(); this.running = false; } /** * Stops time interval measurement * and resets the elapsed time to zero. */ public void reset() { this.startTime = 0; this.stopTime = 0; this.running = false; } /** * Gets the total elapsed time measured * by the current instance, in nanoseconds. * 1 Tick = 100 nanoseconds */ public long getElapsedTicks() { long elapsed; if (running) { elapsed = (System.nanoTime() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed / nsPerTick; } /** * Gets the total elapsed time measured * by the current instance, in milliseconds. * 10000 Ticks = 1 millisecond (1000000 nanoseconds) */ public long getElapsedMilliseconds() { long elapsed; if (running) { elapsed = (System.nanoTime() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed / nsPerMs; } /** * Gets the total elapsed time measured * by the current instance, in seconds. * 10000000 Ticks = 1 second (1000 milliseconds) */ public long getElapsedSeconds() { long elapsed; if (running) { elapsed = (System.nanoTime() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed / nsPerSs; } /** * Gets the total elapsed time measured * by the current instance, in minutes. * 600000000 Ticks = 1 minute (60 seconds) */ public long getElapsedMinutes() { long elapsed; if (running) { elapsed = (System.nanoTime() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed / nsPerMm; } /** * Gets the total elapsed time measured * by the current instance, in hours. * 36000000000 Ticks = 1 hour (60 minutes) */ public long getElapsedHours() { long elapsed; if (running) { elapsed = (System.nanoTime() - startTime); } else { elapsed = (stopTime - startTime); } return elapsed / nsPerHh; } /** * Gets the total elapsed time with format * 00:00:00.0000000 = 00:mm:ss.SSS + 9999 Ticks */ public String getElapsed() { String timeFormatted = ""; timeFormatted = this.formatTime(this.getElapsedTicks()); return timeFormatted; } /** * Gets the total elapsed time with format * 00:00:00.0000000 = 00:mm:ss.SSS + #### Ticks * @param elapsedTicks elapsed ticks between start and stop nano time */ private String formatTime(final long elapsedTicks) { String formattedTime = ""; // should be hh:mm:ss.SSS, but 00 starts with 01 SimpleDateFormat formatter = new SimpleDateFormat("00:mm:ss.SSS"); Calendar calendar = Calendar.getInstance(); if (elapsedTicks <= 9999) { calendar.setTimeInMillis(0); formattedTime = formatter.format(calendar.getTime()) + String.valueOf(String.format("%04d", elapsedTicks)); } else { calendar.setTimeInMillis(elapsedTicks * nsPerTick / nsPerMs); String formattedTicks = String.format("%07d", elapsedTicks); formattedTicks = formattedTicks.substring(formattedTicks.length() - 4); formattedTime = formatter.format(calendar.getTime()) + formattedTicks; } return formattedTime; } }
If we add that class in any Java project, we can now do what the C# code at the beginning of this post does! Let's see the Java version of the code:
package stopwatchapp; import java.math.BigInteger; public class StopwatchApp { public static void main(String[] args) { Stopwatch timer = new Stopwatch(); timer.start(); Fibonacci(50); timer.stop(); System.out.println("Elapsed time in ticks: " + timer.getElapsedTicks()); System.out.println("Elapsed time in milliseconds: " + timer.getElapsedMilliseconds()); System.out.println("Elapsed time in seconds: " + timer.getElapsedSeconds()); System.out.println("Elapsed time in minutes: " + timer.getElapsedMinutes()); System.out.println("Elapsed time in hours: " + timer.getElapsedHours()); System.out.println("Elapsed time with format: " + timer.getElapsed()); } private static BigInteger Fibonacci(int n) { if (n < 2) return BigInteger.ONE; else return Fibonacci(n - 1).add(Fibonacci(n - 2)); } }
And the Output is:
That's it! now I'm ready to work on the next posts using this java timer class. Hope it is helpful to you too since I found lot's of forums asking for it and the answer was always use: System.nanoTime() and System.currentTimeMillis()
By the way, if you want to run the example, change Fibonacci(50) to a lower value such as Fibonacci(35 or 40) to not wait for the result some minutes.