赞
踩
System.currentTimeMillis()
long startTime = System.currentTimeMillis();
// 执行你的代码段
performTask();
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
System.out.println("Execution Time: " + executionTime + " milliseconds");
System.nanoTime()
long startTime = System.nanoTime();
// 执行你的代码段
performTask();
long endTime = System.nanoTime();
long executionTime = (endTime - startTime) / 1000000; // 转换为毫秒
System.out.println("Execution Time: " + executionTime + " milliseconds");
System.nanoTime()
和 TimeUnit
import java.util.concurrent.TimeUnit;
long startTime = System.nanoTime();
// 执行你的代码段
performTask();
long endTime = System.nanoTime();
long executionTime = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
System.out.println("Execution Time: " + executionTime + " milliseconds");
Instant
类(Java 8+)import java.time.Duration;
import java.time.Instant;
Instant start = Instant.now();
// 执行你的代码段
performTask();
Instant end = Instant.now();
long executionTime = Duration.between(start, end).toMillis();
System.out.println("Execution Time: " + executionTime + " milliseconds");
StopWatch
(Apache Commons Lang)如果项目中使用了 Apache Commons Lang 库,可以使用 StopWatch
类来更方便地测量时间:
import org.apache.commons.lang3.time.StopWatch;
StopWatch stopWatch = StopWatch.createStarted();
// 执行你的代码段
performTask();
stopWatch.stop();
System.out.println("Execution Time: " + stopWatch.getTime() + " milliseconds");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。