How Do I Time Things In Java? - Javamex
Maybe your like
There are two standard ways to time operations in Java: System.currentTimeMillis() and System.nanoTime(). Depending on your JVM, there may be other mechanisms available, but these are generally the two standard ways to time things in Java. On this page, we look at the differences between System.currentTimeMillis() and System.nanoTime() and when to use each.
Comparison of System.currentTimeMillis() vs System.nanoTime()
Broadly, either of these calls can serve a similar function to time an operation, using the familiar and logical pattern:
- take the current time and store in a variable;
- perform the operation;
- repeat the call to get the current time again, and subtract from the previously stored time to determine how long the operation took.
However, the two timing calls differ in:
- the resolution (thousanths or billionths of a second) to which the time is reported;
- the actual granularity of measurements;
- the time taken to make the measurement;
- how stable the performance of the timer is;
- whether the time reported means anything in "real life" absolute time and so can be compared across systems and used as time stamps.
The following table summarises System.currentTimeMillis() and System.nanoTime() with respect to these features.
| System.currentTimeMillis | System.nanoTime() | |
|---|---|---|
| Theoretical resolution | 1/1000th of a second | 1/1000,000,000th of a second |
| Typical granularity in practice | Either 1/1000th of a second, or 10 or 15 1/1000ths of a second, depending on system | Around 1/1000,000th of a second (1,000 nanos) |
| Time taken to read | A few clock cycles | 100+ clock cycles |
| Stability | Unstable under Windows: granularity subject to variation. | Stable on a given system. |
| Absolute time? | Yes: value reported is number of millis since 1 Jan 1970 00:00 | No: zero does not necessarily represent any particular reference point. |
Tag » How To Time Things In Java
-
How Do I Time A Method's Execution In Java? - Stack Overflow
-
Measure Elapsed Time In Java - Baeldung
-
Measure Elapsed Time (or Execution Time) In Java - Techie Delight
-
How To Measure Execution Time For A Java Method? - Tutorialspoint
-
How To Measure Elapsed Execution Time In Java - Javarevisited
-
Here's How To Calculate Elapsed Time In Java - Stackify
-
How To Measure Time Taken By A Function In Java ? - GeeksforGeeks
-
How To Calculate Method Execution Time In Java | Edureka Community
-
LocalTime (Java Platform SE 8 ) - Oracle Help Center
-
Elegantly Log Elapsed Time In Java | By Hasan Alsulaiman
-
Java Program To Calculate The Execution Time Of Methods - Programiz
-
Java Program To Calculate Difference Between Two Time Periods
-
Working In Java Time - InfoWorld
-
Java Timer TimerTask Example - DigitalOcean