Measure Execution Time of Code in Seconds using Java

System.currentTimeMillis method

package app;

public class Main
{
    public static void main(String[] args) throws InterruptedException
    {
        long startTime = System.currentTimeMillis();
        doSomething(3);
        long endTime = System.currentTimeMillis();

        float executionTime = (endTime - startTime) / 1000f;
        System.out.printf("%.8f sec", executionTime);
    }

    private static void doSomething(int seconds) throws InterruptedException
    {
        Thread.sleep(seconds * 1000);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.