我最近一直在研究基准测试,我一直对记录程序数据等很感兴趣。我很想知道我们是否可以实现我们自己的内存使用代码并在我们的程序中有效地实现我们自己的时间消耗代码。我知道如何检查代码运行所需的时间:
public static void main(String[]args){
long start = System.currentTimeMillis();
// code
System.out.println(System.currentTimeMillis() - start);
}
我还调查了 Robust Java benchmarking, Part 1: Issues ,这个教程很全面。显示 System.currentTimeMillis();
的负面影响。然后教程建议我们使用 System.nanoTime();
(让它更准确?)。
我也看了Determining Memory Usage in Java用于内存使用。该网站显示了如何实现它。提供的代码看起来效率低下,因为这个人正在调用
long L = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
在此之后,他调用了 System.gc();
(4 * 4) = 16 次。然后再次重复该过程。
这不也占内存吗?
总而言之,是否可以在您的 Java 程序中实现高效的基准测试代码?
最佳答案
是的,可以在 Java 代码中有效地实现性能基准测试。重要的问题是任何类型的性能基准都会增加自己的开销,以及您想要多少。 System.currentMill..() 是足够好的性能基准,在大多数情况下,nanoTime() 是一种矫枉过正。
对于内存,System.gc 将向您显示不同运行的不同结果(因为 gc 运行从未得到保证。)我通常使用 Visual VM 进行内存分析(它是免费的),然后使用 TDA 进行转储分析。
一种侵入性较小的方法是使用面向方面的编程。您可以只创建一个运行在特定注解或一组方法上的切面,并编写一个@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
}
}
关于java - Java 代码内部基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8423789/