简体   繁体   English

计算Java程序的执行时间

[英]Calculate Execution Time of Java Program

I want to compute the execution time of my Java Program and I am confused how I should go about it. 我想计算我的Java程序的执行时间,我很困惑我应该怎么做。 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. 我知道可以使用System.nanoTime()和System.currentTimeInMillis()计算经过的时间,但是这种方法没有考虑操作系统的基础调度机制。

For example : Say there are 3 processes running at the same time (lets assume its a single core system) 例如:假设有3个进程同时运行(假设它是一个单核心系统)

Process A 过程A.

Process B (My Java Code - running in JVM Process) 进程B(我的Java代码 - 在JVM进程中运行)

Process C 过程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. 现在,如果进程B在上午11:00开始执行并在上午11:02完成执行,则System.nanoTime()和System.currentTimeInMillis()将报告所花费的时间为2分钟。 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. 但是,过程B可能不会在整个2分钟的持续时间内运行,因为操作系统将安排另外2个进程,并且它们将在2分钟的时间间隔内运行一段时间。 So in essence the java Program would run for less than 2 minutes. 所以本质上java程序运行不到2分钟。

Is there some way to pinpoint the exact time that was taken by a Java Program itself to complete execution? 有没有办法确定Java程序本身完成执行所花费的确切时间? 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. 如果您使用的是Java 8,那么它具有Instant类,它代表时间线上的瞬时点。 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 它打印: PT7.001S

The old fashion way is... Break it into methods 旧的时尚方式是......把它分解成方法

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

long duration = endTime - startTime;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM