I created a presentation rendering framework using java. In need to calculate how much time taken by the user for the each frame in the presentation. So is there is any api or framework in java which looks like a stopwatch.
-
Might be a duplicate: http://stackoverflow.com/questions/21694833/how-to-display-and-compute-time-in-java/21695317#21695317 – Spindizzy Feb 26 '14 at 07:06
-
Yep, `System.currentTimeMillis()` :) – Svetlin Zarev Feb 26 '14 at 07:08
-
1You cannot reliably use `System.currentTimeMillis()` for measuring time, see here: http://stackoverflow.com/questions/351565 – Feb 26 '14 at 07:26
2 Answers
For measurement you could use:
System.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.
for example from oracle documentation:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;

- 8,567
- 3
- 26
- 43
Use System.nanoTime()
which exists precisely for this purpose. If you want extra goodies
like easy manipulation of elapsed time, support for laps, then you can have a look at the com.google.common.base.StopWatch
in the Guava library.
Example:
Stopwatch stopwatch = Stopwatch.createStarted();
doSomething();
stopwatch.stop(); // optional
long millis = stopwatch.elapsed(MILLISECONDS);
log.info("time: " + stopwatch); // formatted string like "12.3 ms"
Guava also includes other goodies like collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth.