我的java代码执行了许多查询。对于每个查询,我需要监视执行时间。此外,我还需要监视某些功能的执行时间。那么,有没有办法这样做,以一种优雅的方式?
发布于 2013-11-21 15:31:25
有一个开源项目可以做到这一点。下面是其中的一个示例代码片段。
private final static int BASIC_STOPWATCH_ID =
Audits.mapAudit("example.basicStopwatch");
public void tryOut(){
final Stopwatch stopwatch = Audits.getBasicStopwatch(BASIC_STOPWATCH_ID);
stopwatch.start();
doSomeWork();
stopwatch.stop();
}审计在github上。
发布于 2013-11-21 15:38:09
Perf4J是这方面的最佳解决方案。
Perf4J是一个开源工具集,用于添加Java服务器端代码定时语句以及记录、分析和监视结果。对于那些熟悉日志框架(如log4j或java.util.logging )的开发人员来说,一个类推可以帮助描述Perf4J:
Perf4J是System.currentTimeMillis(),log4j是System.out.println()
如需进一步参考,请访问http://www.infoq.com/articles/perf4j
发布于 2013-11-21 17:20:37
如果要度量方法的执行时间,还可以使用Java的System.nanoTime()方法。它使用平台上可用的最高分辨率定时器。时间是相对的“空闲运行时间”,只能与其他nanoTime值进行比较。(钟)
但是,非常重要的是要记住,Java需要一个重要的时间来“热身”。Java在JVM (Java Virtual )中运行其编译过的字节码,并使用它的JIT (刚好是及时的编译器)在运行时优化字节码的部分内容,以提高性能。
如果您想要精确地测量执行速度,应该多次运行您的函数,并且不要使用第一次运行的测量次数。例如,下面的代码:
import java.util.Random;
import tools.Helpers;
public class DivideInlineShort {
public static void main(String[] args) {
int n = args.length > 0 ? Integer.parseInt(args[0]) : 10000;
Random r = new Random();
for (int i = 0; i < 50; i++)
runTest(n, r.nextInt(8) + 1); // you need the random to prevent the JVM removing the loops
}
public static void runTest(int n, int ran) {
int counter = 0;
long timeStart = System.nanoTime();
for (int j = 0; j < n; j++)
for (int i = ran; i < 100000 + ran; i++)
counter += return1(i);
long timeEnd = System.nanoTime();
System.out.println(
Helpers.roundedTimeInMillis(timeStart, timeEnd) + "\t\t" + counter);
}
public static int return1(int i) {
return i / i;
}
}最初的2到3次运行占用了我的机器大约700毫秒,而剩下的47次大约370毫秒。这可以解释,因为内联优化在调用方法超过10.000次(如果我没有记错的话)之后就开始了。
因此,如果您想要精确地度量代码的执行时间,应该在同一个JVM实例上多次运行它,而忽略前几轮。
https://stackoverflow.com/questions/20125032
复制相似问题