KP6*_*P65 44 java optimization
我有一个程序,我自己用java编写,但我想测试方法执行时间并获得特定方法的时间.我想知道这是否可能,或许某种程度上是一个eclipse插件?或者可能插入一些代码?
我知道,这是一个相当小的程序,不超过1500行,这将是一个更好的专用工具或System.currentTimeMillis()?
非常感谢
Chr*_*ght 46
除了使用分析器之外,获得所需内容的简单方法如下:
public class SomeClass{
public void somePublicMethod()
{
long startTime = System.currentTimeMillis();
someMethodWhichYouWantToProfile();
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime-startTime) + "ms");
}
}
Run Code Online (Sandbox Code Playgroud)
El *_*rce 22
如果瓶颈大到足以使用分析器观察,请使用分析器.
如果您需要更高的准确性,测量一小段代码的最佳方法是使用Java微基准框架,如OpenJDK的JMH或Google的Caliper.我相信它们和JUnit一样简单,不仅可以获得更准确的结果,而且您将从社区获得专业知识.
遵循JMH微基准测试来测量执行时间Math.log():
private double x = Math.PI;
@Benchmark
public void myBenchmark() {
return Math.log(x)
}
Run Code Online (Sandbox Code Playgroud)
使用currentMillis()和nanoTime()测量有许多限制:
Java中的currentMillis()和nanoTime()方法可能很有用,但必须与EXTREME小心一起使用,否则您可能会出现错误的测量错误,例如测量片段的顺序会影响测量,或者像这样,作者错误地断定数百万次操作在实际上,JMV实现了没有进行任何操作并提升代码,根本不运行任何代码.
这是一个精彩的视频,解释了如何以正确的方式进行微基准测试:https://shipilev.net/#benchmarking
对于快速和肮脏的时间测量测试,不要使用挂钟时间 ( System.currentTimeMillis())。更喜欢System.nanoTime():
public static void main(String... ignored) throws InterruptedException {
final long then = System.nanoTime();
TimeUnit.SECONDS.sleep(1);
final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - then);
System.out.println("Slept for (ms): " + millis); // = something around 1000.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32452 次 |
| 最近记录: |