2016-02-28 141 views
1

我想测量完整的执行时间(所以当所有线程完成时)。 System.currentimeMillis的技巧在这里不起作用,因为当main方法结束时,我自己创建的线程仍然会运行,因为它们比main方法处理需要更长的时间。 我该怎么做?测量多线程的执行时间

我举个例子。

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

回答

2

您可以使用ExecutorService

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

然后不要忘记shutdown()

发起在以前已提交任务的执行一个有序的关闭,但没有新的任务将被接受。如果已关闭,调用没有其他影响。

executorService.shutdown(); 

而且wait

关机请求后

阻塞,直到所有任务完成执行,或发生超时,或者当前线程中断,无论哪一个首先发生。

executorService.awaitTermination(1, TimeUnit.HOUR); // however long you need 

然后计算:

long totalTime = System.nanoTime() - startTime; 

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

你应该考虑测量结束时间之前使用thread Joins。这将确保主线程仅在所有其他线程退出时退出。

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

}

输出在这种情况下应该是:

线程了:5003ms

+0

让我知道,如果这有助于。 – Learner