Calculate the execution time of the Java program

I want to compute the execution time of my Java Program and I am confused how I should go about it. I know that time elapsed can be computed using System.nanoTime() & System.currentTimeInMillis(), however this approach does not take into consideration the underlying scheduling mechanism of the Operating System.

For example : Say there are 3 processes running at the same time (lets assume its a single core system)

Process A

Process B (My Java Code - running in JVM Process)

Process C

Now if Process B starts executing at 11:00 AM and completes execution at 11:02 AM, System.nanoTime() & System.currentTimeInMillis() will report the time taken as 2 minutes. However its possible that Process B might not be running for the duration of entire 2 minutes, because the OS will schedule the other 2 Process and they would be running for some amount of time in the 2 minute interval. So in essence the java Program would run for less than 2 minutes.

Is there some way to pinpoint the exact time that was taken by a Java Program itself to complete execution? Note :

  1. We can run the code multiple times and take average time to minimize the effects of such cases, still it would be good to know if there is some reliable way to compute the execution time

  2. Lets assume that the portion of code that we need to time cannot be broken into smaller chunks and takes a large amount of time to process.


Just in case you are using Java 8 then it has Instant class which represents an instantaneous point on the time-line. This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application as:

    Instant start = Instant.now();
    try {
        Thread.sleep(7000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Instant end = Instant.now();
    System.out.println(Duration.between(start, end));
}

And it prints: PT7.001S