问题
这个问题在这里已有答案:
如何计算方法在Java中的执行时间? 36个答案
如何计算在Java中执行方法所需的时间?
#1 热门回答(192 赞)
你可以在之前和之后拍摄时间戳快照,然后重复几次实验以平均到结果.还有一些分析器可以为你执行此操作。
##来自"Java平台性能:策略与策略"一书:
使用System.currentTimeMillis()
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
使用StopWatch类
你可以使用此StopWatch类,并在方法之前和之后调用start()和stop。
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
Seehere。
NetBeans Profiler:
应用程序性能应用程序性能配置文件方法级CPU性能(执行时间)。你可以选择分析整个应用程序或应用程序的一部分。
Seehere。
#2 热门回答(181 赞)
更确切地说,我会使用13250105方法而不是currentTimeMillis():
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
在Java 8中(输出格式为ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed for myCall() is "+ stopwatch.elapsed(MILLISECONDS));
#3 热门回答(32 赞)
有了这个,你可以通过以下方式计算方法的时间:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;