how can I find execution time of multi threaded application

依然范特西╮ 提交于 2020-04-18 04:42:11

问题


After execution of below code I am getting time as 0 , because time calculation is present in main thread and it is calculating durationTime value and then executing threadPool.

I wants to find total time taken while executing threads.

public static void main(String[] args) {
        long startTime = System.nanoTime(); 
        int numberThread=10;
        String apiToBeCall="abcApi";

        Runnable r1=new SFSrmMainClass(apiToBeCall);

        ExecutorService threadPool=Executors.newFixedThreadPool(numberThread);
        for (int i=0;i<numberThread;i++)
        {

            threadPool.execute(r1);
        }
        threadPool.shutdown();

        long endTime = System.nanoTime();
         long durationTime = (endTime - startTime); 
        System.out.println("time for "+apiToBeCall +" is having thread="+numberThread +" is "+durationTime/1000000000);
    }

回答1:


Use awaitTermination after calling shutdown(), which blocks the main thread until all threads finished.

Example:

static long measureTasks(final int nThreads, final Runnable... tasks) 
    throws InterruptedException
{
    final ExecutorService pool = Executors.newFixedThreadPool(nThreads);
    final long startTime = System.nanoTime();

    for (Runnable task : tasks)
        pool.execute(task);

    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);

    return System.nanoTime() - startTime;
}


来源:https://stackoverflow.com/questions/27902200/how-can-i-find-execution-time-of-multi-threaded-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!