是的,可以在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{}@Aspectclass PerformanceAspect{ @Around("the pointcut expression to pick up all " + "the @PerfMonitor annotated methods") public void logPerformance(){ // log performance here // Log it to a file }}


