简体   繁体   中英

Measuring execution time over multiple threads

I want to measure the full execution time (so when ALL threads are done). The trick with System.currentimeMillis won't work here, because when the main-method ends, my own created threads will still be running because they take longer time to process than the main-method. How Can I do this?

I'll give an example.

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.
}
}

You can use an ExecutorService :

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

Then don't forget to 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();

And 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

Then calculate:

long totalTime = System.nanoTime() - startTime; 

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

You should consider using thread Joins before measuring the end time. That will ensure that the main thread exit only when all other threads exit.

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");
}

}

Output in this case should be:

The thread took:5003ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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