2015-04-01 58 views
5

我试图测试webcrawler的性能(在执行时间方面),但由于发生多线程,我无法对其进行计时。如何计算多线程程序的运行时间?

我的主类:

class WebCrawlerTest { 
    //methods and variables etc 
    WebCrawlerTest(List<String> websites){ 
    // 
    } 

    if(!started){ 
     startTime = System.currentTimeMillis(); 
     executor = Executors.newFixedThreadPool(32); //this is the value I'm tweaking 
     started=true; 
    }  
    for(String site : websites){ 
     executor.submit(webProcessor = new AllWebsiteProcessorTest(site, deepSearch)); 
    }        
    executor.shutdown(); 
    //tried grabbing end time here with no luck 

AllWebsiteProcessorTest类:

class AllWebsiteProcessorTest implements Runnable{ 
    //methods and var etc 

    AllWebsiteProcessorTest(String site, boolean deepSearch) { 
    } 
    public void run() {   
     scanSingleWebsite(websites); 
     for(String email:emails){ 
      System.out.print(email + ", "); 
     } 

private void scanSingleWebsite(String website){ 
    try { 
     String url = website; 
     Document document = Jsoup.connect(url).get(); 
     grabEmails(document.toString()); 
    }catch (Exception e) {} 

随着另一个类(具有main方法),I创建的WebCrawlerTest的实例,然后通过在网站阵列。爬虫工作正常,但我似乎无法弄清楚如何计时。

我可以得到开始时间(System.getCurrentTime...();),但问题是结束时间。我试过添加这样的结束时间:

//another class 
public static void main(.....){ 
    long start = getCurrent....(); 
    WebCrawlerTest w = new WebCrawlerTest(listOfSites, true); 
    long end = getCurrent....(); 
} 

哪一个不起作用。我也尝试在executor.shutdown()之后添加end,这个功能再次不起作用(即刻触发)。我如何获得最终完成线程的时间?

+1

您可以将'Runnable'变成'Callable',其返回结果是完成时间戳,然后通过'Future#get()' – 2015-04-01 08:55:56

回答

5

关停后,你的遗嘱执行人集中

executor.shutdown(); 
//tried grabbing end time here with no luck 

你可以简单地

executor.awaitTermination(TimeUnit, value) 

此调用将阻塞,直到所有的任务都完成。花时间,从它减去T0,瞧,我们有执行时间。

shutdown()方法只是确保没有新的任务将被接受到excution队列中。已经在队列中的任务将被执行(shutdownNow()丢弃未决任务)。要等待所有正在运行的任务完成,您必须登录awaitTermination()

+0

汇总此时间戳,我正在寻找,并感谢您的额外信息! :-)! 'shutdownNow()'是另一种方法,我将在不久的将来需要! – gudthing 2015-04-01 09:00:30

+0

我很高兴我能帮上忙。 – Antoniossss 2015-04-01 09:08:30