long start = System.currentTimeMillis();
// 待測試代碼
// ...
long end = System.currentTimeMillis();
long elapsedMs = end - start;
System.out.println("耗時: " + elapsedMs + " ms");
long start = System.nanoTime();
// 待測試代碼
// ...
long end = System.nanoTime();
long elapsedNs = end - start;
double elapsedMs = elapsedNs / 1_000_000.0;
System.out.printf("耗時: %.3f ms%n", elapsedMs);
nanoTime() 返回 JVM 高精度時間源,**無關系統時鐘**,專為測量間隔設計,不受系統時間調整影響。
手動計時受 JIT 編譯、GC、CPU 頻率縮放等干擾大。標準做法使用 JMH (Java Microbenchmark Harness):
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(3)
@State(Scope.Benchmark)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 待測代碼
}
}
Maven 依賴:
org.openjdk.jmh
jmh-core
1.37
org.openjdk.jmh
jmh-generator-annprocess
1.37
若確需在運行時知道「構建時間」,可在構建腳本中寫入資源文件:
maven-resources-plugin 過濾 build.properties 寫入 ${maven.build.timestamp}。processResources 任務中 expand(buildTime: new Date())。System.nanoTime()** (高精度) 或 currentTimeMillis() (粗略)。