3 回答

TA贡献1803条经验 获得超3个赞
您可以在前后拍摄时间戳快照,然后重复几次实验以求平均值。也有分析器可以为您执行此操作。
摘自《 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类,并调用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());
}
}
看这里。
NetBeans探查器:
应用性能应用
性能配置文件方法级别的CPU性能(执行时间)。您可以选择分析整个应用程序或应用程序的一部分。
看这里。

TA贡献1895条经验 获得超3个赞
更确切地说,我将使用nanoTime()method而不是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: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));

TA贡献1798条经验 获得超7个赞
检查以下内容:System.currentTimeMillis。
这样,您可以通过执行以下操作来计算方法的时间:
long start = System.currentTimeMillis();
class.method();
long time = System.currentTimeMillis() - start;
添加回答
举报