Calculating Execution Time in Java: Methods and Real-world Examples

Measuring the execution time of code is essential for optimizing performance in Java applications. It helps developers identify bottlenecks and improve efficiency. This article explores common methods to calculate execution time and provides practical examples.

Using System.nanoTime()

The System.nanoTime() method offers high-resolution time measurement. It returns the current value of the most precise available system timer, in nanoseconds. To measure execution time, record the start time before the code runs and the end time afterward. The difference indicates the elapsed time.

Example:

long startTime = System.nanoTime();

// code to measure

long endTime = System.nanoTime();

long duration = endTime – startTime;

Using System.currentTimeMillis()

The System.currentTimeMillis() method provides the current time in milliseconds. It is less precise than nanoTime() but suitable for measuring longer durations. Similar to the previous method, record the start and end times around the code block.

Example:

long startTime = System.currentTimeMillis();

// code to measure

long endTime = System.currentTimeMillis();

long duration = endTime – startTime;

Using Java’s Instant Class

The Instant class from the java.time package offers a modern approach to time measurement. It provides nanosecond precision and is suitable for measuring durations.

Example:

Instant start = Instant.now();

// code to measure

Instant end = Instant.now();

Duration duration = Duration.between(start, end);

Real-world Example

Suppose you want to measure how long it takes to sort a large array. Using System.nanoTime(), you can implement the following:

int[] array = new int[1_000_000];

// populate array

long startTime = System.nanoTime();

Arrays.sort(array);

long endTime = System.nanoTime();

System.out.println(“Sorting took ” + (endTime – startTime) + ” nanoseconds.”);