To get the elapsed time in Java, you can use the System.nanoTime
method or the Instant.now
method of the java.time
package.
Here is an example of how to get the elapsed time in Java using the System.nanoTime
method:
long startTime = System.nanoTime(); // code to be measured goes here long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; System.out.println(elapsedTime + " nanoseconds");
In this example, the System.nanoTime
method is used to get the current time in nanoseconds since the epoch (the point in time at which the time is 0). The startTime
variable is initialized with the current time before the code to be measured is executed. After the code has been executed, the endTime
variable is initialized with the current time again. The elapsed time is then calculated by subtracting the startTime
from the endTime
and storing the result in the elapsedTime
variable. The elapsedTime
variable is then printed to the console using the println
method of the System.out
object.
This example will output a long integer value similar to the following to the console:
1234 nanoseconds
Which represents the elapsed time in nanoseconds.
You can also use the Instant.now
method of the java.time
package to get the elapsed time as a Duration
object:
import java.time.Duration; import java.time.Instant; Instant startTime = Instant.now(); // code to be measured goes here Instant endTime = Instant.now(); Duration elapsedTime = Duration.between(startTime, endTime); System.out.println(elapsedTime + " seconds");
In this example, the Instant.now
method is used to get the current time as an Instant
object. The startTime
variable is initialized with the current time before the code to be measured is executed. After the code has been executed, the endTime
variable is initialized with the current time again. The elapsed time is then calculated by calling the Duration.between
method and passing it the startTime
and endTime
variables. The resulting Duration
object is stored in the elapsedTime
variable and printed to the console using the println
method of the System.out
object.
This example will output a string similar to the following to the console:
PT0.001234S
Which represents the elapsed time in the ISO-8601 format.
You can use these methods to measure the elapsed time of a specific code block in your Java applications. You can then use the java.time
package or other libraries to manipulate and format the elapsed time as needed.