user3558691
user3558691

Reputation: 117

Capture Total Execution time of a parallel thread

I am using java.util.concurrent.Executors and java.util.concurrent.ExecutorService to execute parallel threads. Please let me know how to capture Time taken for complete all threads.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CallBackTest {
    private static int NUM_OF_TASKS = 50;
       Object result;
       int cnt = 0;
       long begTest, endTest;

       public CallBackTest() {   }

       public void callBack(Object result) {
              System.out.println("result "+result);
              this.result = result;
           }


       public void run() {

              ExecutorService es = Executors.newFixedThreadPool(50);
              for(int i = 0;  i < NUM_OF_TASKS; i++) {

                 CallBackTask task = new CallBackTask(i);
                 task.setCaller(this);
                 es.submit(task);
                 // at this point after submitting the tasks the
                 // main thread is free to perform other work.
              }
           }

       public static void main(String[] args) {
              new CallBackTest().run();
           }
    }

Upvotes: 0

Views: 1612

Answers (1)

Mani
Mani

Reputation: 3364

Create Simple Task as

public class SimpleTask implements Runnable {
    AtomicLong totalTime;
    public SimpleTask(AtomicLong totalTime) {
        this.totalTime = totalTime;
    }
    @Override
    public void run() {
        long currentTime = System.nanoTime();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        totalTime.addAndGet(System.nanoTime()-currentTime);
    }
}

// Main Pass AtomicLong to each task to capture the time taken for that thread. and sum it to the same instance. AtomicLong is thread safe.

           AtomicLong totalTime = new AtomicLong(0);
        long currentTime = System.nanoTime();
        ExecutorService executor = Executors.newFixedThreadPool(numberofThread);
        for (int i = 0; i < numberofTasks; i++) {
            SimpleTask task = new SimpleTask(totalTime);
            executor.submit(task);
        }
        executor.shutdown();

// Wait until all the threads completed.

try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {}

// Calculate the time

System.out.println("Overall time"+ (System.nanoTime()-currentTime));

// Get the value from Atomic Long

    System.out.println("All Threads Spent time"+ totalTime);

Upvotes: 1

Related Questions