Jee*_*hah 18 java performance benchmarking
我最近一直在研究基准测试,我一直对记录程序数据等感兴趣.我有兴趣知道我们是否可以实现自己的内存使用代码并在我们的程序中有效地实现我们自己的时间消耗代码.我知道如何检查代码运行所需的时间:
public static void main(String[]args){
long start = System.currentTimeMillis();
// code
System.out.println(System.currentTimeMillis() - start);
}
Run Code Online (Sandbox Code Playgroud)
我还研究了Robust Java基准测试,第1部分:问题,本教程非常全面.显示的负面影响System.currentTimeMillis();.然后教程建议我们使用System.nanoTime();(使其更准确?).
我还研究了使用Java确定内存使用情况以获取内存使用情况.该网站显示了如何实施它.提供的代码看起来无穷无尽,因为此人正在呼叫
long L = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
在此之后,他打电话给System.gc();(4*4)= 16次.然后再次重复该过程.这不也占用记忆吗?
那么在结论中,是否可以在java程序中实现高效的基准测试代码?
Viv*_*vek 11
是的,可以在java代码中有效地实现性能基准测试.重要的问题是,任何类型的性能基准测试都会增加自己的开销,以及您想要多少.System.currentMill ..()是性能良好的基准,在大多数情况下,nanoTime()是一种矫枉过正.
对于内存System.gc将显示不同运行的不同结果(因为gc run从不保证.)我通常使用Visual VM进行内存分析(免费),然后使用TDA进行转储分析.
一种较少侵入性的方法是使用面向方面的编程.您可以只创建一个在特定注释或方法集上运行的Aspect,并编写@Around建议来收集性能数据.
这是一个小片段:
public class TestAspect {
@LogPerformance
public void thisMethodNeedsToBeMonitored(){
// Do Something
}
public void thisMethodNeedsToBeMonitoredToo(){
// Do Something
}
}
@interface LogPerformance{}
@Aspect
class PerformanceAspect{
@Around("the pointcut expression to pick up all " +
"the @PerfMonitor annotated methods")
public void logPerformance(){
// log performance here
// Log it to a file
}
}
Run Code Online (Sandbox Code Playgroud)