Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
}
}
like image 464
Domien Avatar asked Oct 18 '25 01:10

Domien


2 Answers

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);
like image 182
Idos Avatar answered Oct 19 '25 13:10

Idos


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

like image 33
The Roy Avatar answered Oct 19 '25 14:10

The Roy