我有两种不同的方法,它们实际上执行相同的操作,但实现方式略有不同。他们遍历一个目录并读取其中的所有文件,并检查该目录中有多少具有特定名称的文件。现在我想知道哪个更快,但两者相似,大约需要 3-4 秒(目录有数百万个文件),但我怎么知道哪个真的更快?有没有一种方法可以比较它们的速度?
方法)
private void getAllRelatedFilesEig(String corrId) throws InterruptedException, IOException { log.debug("Get all files with corrId=" + corrId + " from directory=" + processingDir); Profiler profiler = Profiler.createStarted(); Files.list(Paths.get(processingDir)) .filter(p -> p.getFileName().toString() .indexOf("EPX_" + corrId + "_") >= 0) .forEach( path -> { try { EPEXFile file = new EPEXFile(path); if (file.isTranMessage()) { if (file.isOrderMessage()) { orderFiles.add(file); } else { tradeFiles.add(file); } } else { infoFiles.add(file); } } catch (IFException ex) { log.error("Error creating EPEXFile object " + ex.getMessage()); } } ); profiler.stop("allFilesWithSameCorrIdRetrieval"); log.info(orderFiles.size() + " order files with corrId=" + corrId); log.info(tradeFiles.size() + " trade files with corrId=" + corrId); log.info(infoFiles.size() + " info files with corrId=" + corrId); profiler = Profiler.createStarted(); profiler.stop("processFiles"); orderFiles.clear(); tradeFiles.clear(); infoFiles.clear(); }
方法)
private void getAllRelatedFilesOrig(String corrId) throws InterruptedException, IOException { log.debug("Get all files with corrId=" + corrId + " from directory=" + processingDir); Path dirPath = Paths.get(processingDir); ArrayList<Path> fileList; Profiler profiler = Profiler.createStarted(); try (Stream<Path> paths = Files.walk(dirPath)) { fileList = paths.filter(t -> (t.getFileName().toString().indexOf("EPX_" + corrId + "_") >= 0)) .collect(Collectors.toCollection(ArrayList::new)); for (Path path : fileList) { try { EPEXFile file = new EPEXFile(path); if (file.isTranMessage()) { if (file.isOrderMessage()) { orderFiles.add(file); } else { tradeFiles.add(file); } } else { infoFiles.add(file); } } catch (IFException ex) { log.error("Error creating EPEXFile object " + ex.getMessage()); } } } profiler.stop("allFilesWithSameCorrIdRetrieval"); log.info(orderFiles.size() + " order files with corrId=" + corrId); log.info(tradeFiles.size() + " trade files with corrId=" + corrId); log.info(infoFiles.size() + " info files with corrId=" + corrId); profiler = Profiler.createStarted(); profiler.stop("processFiles"); orderFiles.clear(); tradeFiles.clear(); infoFiles.clear(); }
我试图用 Profiler 类来解决这个问题,但我无法弄清楚哪个更快,因为有时第一个更快,有时第二个更快。有没有办法说哪个总体上更快?即使它只是快一点点,它也会帮助我知道它是哪一个。
最佳答案
我最近编写了这个方法来测试我的两个方法,它们以不同的方式完成完全相同的事情。
private void benchMark(){
long t, t1=0, t2 =0;
for (int i =0; i< 50; i++){
t= System.currentTimeMillis();
method1();
t1 += System.currentTimeMillis()-t;
t= System.currentTimeMillis();
method2();
t2+= System.currentTimeMillis()-t;
}
System.out.println("Benchmarking\n\tMethod 1 took + "+t1+" ms\n\tMethod 2 took "+t2+" ms");
}
这是一种粗暴的方法,但它确实有效,因为我发现我的一种方法在每次测试中始终快了约 5%。
我依次调用这些方法来减少测试期间性能变化的影响。
关于java - 比较两种java方法的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154747/