测量多个线程的执行时间

Measuring execution time over multiple threads

我想测量完整的执行时间(所以当所有线程都完成时)。 System.currentimeMillis 的技巧在这里不起作用,因为当 main-method 结束时,我自己创建的线程仍将是 运行 因为它们比 main-method 需要更长的时间来处理。 我该怎么做?

我举个例子

public class Main {

public static void main(String[] args) {

    long start = System.currentTimeMillis();

    new Thread(() -> {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();

    long end = System.currentTimeMillis();

    System.out.println(end - start); // Won't work because my new Thread will still be running here.
}
}

您可以使用 ExecutorService:

long startTime = System.nanoTime();
ExecutorService executorService = Executors.myPool();
for(conditions)
   executorService.submit(new myThread());

那么别忘了shutdown():

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

executorService.shutdown();

wait

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

executorService.awaitTermination(1, TimeUnit.HOUR); // however long you need

然后计算:

long totalTime = System.nanoTime() - startTime; 

System.out.printf("The total time everything took was %.3f ms %n", totalTime/1e6);

您应该考虑在测量结束时间之前使用 thread Joins。这将确保仅当所有其他线程退出时主线程才退出。

package threadsync;

public class MeasureRunningTime {

public static void main(String[] args) {

    long start = System.currentTimeMillis();

    Thread th = new Thread(){ 
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
    };

    th.start();

    try {
        th.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long end = System.currentTimeMillis();

    System.out.println("The thread took:" +  (end - start) + "ms");
}

}

这种情况下的输出应该是:

线程took:5003ms