Java Measure Time For Code Execution

If we want to measure time of code execution then we can get the time as long (in milliseconds) before and after specific code execution and find the difference which will give us the answer how long a code execution take.

Lest see example program:

package org.example;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Start of the program");

        final long startTime = System.currentTimeMillis();
        // Here the measurements are done
        // For testing reasons we make the thread sleep for 1 second
        final long endTime = System.currentTimeMillis();

        System.out.println("Execution time in milliseconds: " + (endTime - startTime));

And the result is:

Start of the program
Execution time in milliseconds: 1000

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.