我正在尝试测试我的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
方法),我创建了WebCrawlerTest
的实例,然后传入一系列网站。爬虫工作正常,但我似乎无法弄清楚如何计时。
我可以得到开始时间(System.getCurrentTime...();
),但问题是结束时间。我试过像这样添加结束时间:
//another class
public static void main(.....){
long start = getCurrent....();
WebCrawlerTest w = new WebCrawlerTest(listOfSites, true);
long end = getCurrent....();
}
哪个不起作用。我还尝试在end
之后添加executor.shutdown()
,这再次无效(立即触发)。如何获取最终完成的主题的时间?
答案 0 :(得分:5)
关闭执行程序池后
executor.shutdown();
//tried grabbing end time here with no luck
你可以简单地
executor.awaitTermination(TimeUnit, value)
此调用将阻止所有任务完成。花点时间,从中减去T0
,瞧,我们有执行时间。
shutdown()
方法只是确保没有新任务被接受到执行队列中。将执行队列中已有的任务(shutdownNow()
删除待处理的任务)。要等待所有当前正在运行的任务完成,您必须awaitTermination()
。