【发布时间】:2012-03-15 16:56:28
【问题描述】:
我有一个简单的课程,我想测量方法调用时间,我该怎么做?寻找实现这一目标的通用方法,以便我也可以将其应用于更困难的课程。谢谢
import java.io.*;
import java.util.*;
public class Turtle {
private String name;
private Formatter f;
public Turtle(String name, Formatter f) {
this.name = name;
this.f = f;
}
public void move(int x, int y) {
f.format("%s The Turtle is at (%d,%d)\n", name, x, y);
}
public static void main(String[] args) {
PrintStream outAlias = System.err;
Turtle tommy = new Turtle("Tommy",
new Formatter(System.out));
Turtle terry = new Turtle("Terry",
new Formatter(outAlias));
tommy.move(0,0);
terry.move(4,8);
tommy.move(3,4);
terry.move(2,5);
tommy.move(3,3);
terry.move(3,3);
}
}
【问题讨论】:
-
你是什么意思,“方法调用时间”?
-
正如其中一位 ppl 所说,现在是 CPUT 时间。我想知道是否有任何 Java 内置方法。不是在寻找任何复杂的东西,比如探查器,而是我可以在我的代码中临时使用的东西。像这样:long startTime = System.currentTimeMillis(); tommy.move(0,0); long endTime = System.currentTimeMillis(); System.out.println("That takes " + (endTime - startTime) + " milliseconds");//但是有没有办法用一些Java方法在一行中做到这一点?
-
@aretal 您的示例测量的是经过(墙)时间,而不是 CPU 时间。显然很难在一行中做到这一点,因为您至少需要标记时钟应该以某种方式开始和停止的行。 Aspects 可以为您提供一个紧凑的解决方案,但如果您只想测量时间,那么深入研究 AOP 可能有点过头了。
-
是的,我了解我的解决方案的局限性,这就是为什么希望有更好的解决方案。它似乎是AOP。还是谢谢你