测量Java方法的执行时间

如何计算在Java中执行方法所花费的时间?



qq_花开花谢_0
浏览 624回答 3
3回答

繁星点点滴滴

您可以在前后拍摄时间戳快照,然后重复几次实验以求平均值。也有分析器可以为您执行此操作。摘自《 Java平台性能:战略与策略》一书:使用System.currentTimeMillis()class TimeTest1 {&nbsp; &nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; long startTime = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; long total = 0;&nbsp; &nbsp; &nbsp; for (int i = 0; i < 10000000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;total += i;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; long stopTime = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; long elapsedTime = stopTime - startTime;&nbsp; &nbsp; &nbsp; System.out.println(elapsedTime);&nbsp; &nbsp;}}带有秒表课程你可以使用这个StopWatch类,并调用start()和stop之前和方法之后。class TimeTest2 {&nbsp; &nbsp;public static void main(String[] args) {&nbsp; &nbsp; &nbsp; Stopwatch timer = new Stopwatch().start();&nbsp; &nbsp; &nbsp; long total = 0;&nbsp; &nbsp; &nbsp; for (int i = 0; i < 10000000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;total += i;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; timer.stop();&nbsp; &nbsp; &nbsp; System.out.println(timer.getElapsedTime());&nbsp; &nbsp;}}看这里。NetBeans探查器:应用性能应用性能配置文件方法级别的CPU性能(执行时间)。您可以选择分析整个应用程序或应用程序的一部分。看这里。

蛊毒传说

更确切地说,我将使用nanoTime()method而不是currentTimeMillis():long startTime = System.nanoTime();myCall();&nbsp;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(); // optionalSystem.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));

元芳怎么了

检查以下内容:System.currentTimeMillis。这样,您可以通过执行以下操作来计算方法的时间:long start = System.currentTimeMillis();class.method();long time = System.currentTimeMillis() - start;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java