我如何找到多线程应用程序的执行时间 [英] how can I find execution time of multi threaded application
本文介绍了我如何找到多线程应用程序的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
执行以下代码后,我将时间设为0,因为时间计算存在于主线程中,并且正在计算durationTime值,然后执行threadPool.
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);
}
推荐答案
Use awaitTermination after calling shutdown(), which blocks the main thread until all threads finished.
示例:
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;
}
这篇关于我如何找到多线程应用程序的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文