Calculate Java program runtime

I want to calculate the runtime of my Java program, and I am confused about how I should do this. I know that elapsed time can be calculated using System.nanoTime () and System.currentTimeInMillis (), however this approach does not take into account the basic mechanism for planning the operating system.

For example: let's say that there are three processes that are running at the same time (suggesting that this is one core)

Process a

Process B (my Java code - runs in the JVM process)

Process c

Now, if Process B starts execution at 11:00 and ends execution at 11:02, System.nanoTime () and System.currentTimeInMillis () will report the time taken for 2 minutes. However, it is possible that process B may not work for as long as 2 minutes, since the OS will schedule another process 2, and they will work for a while for a 2-minute interval. Thus, essentially a Java program will run for less than 2 minutes.

Is there a way to determine the exact time that the Java program itself executed to complete the execution? Note:

  • We can run the code several times and take the average time to minimize the consequences of such cases, but it would be nice to know if there is any reliable way to calculate the runtime

  • , , , .

+3
2

, Java 8, Instant, . . :

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

: PT7.001S

+6

...

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = endTime - startTime;
+3

All Articles