| 方法 | 返回值 | 精度 | 用途 | 注意事項 |
|---|---|---|---|---|
System.currentTimeMillis() | long (ms) | 毫秒 (實際精度依 OS,通常 10-15ms) | 壁鐘時間、日期時間、長耗時任務、日誌時間戳 | 受系統時間調整影響 (NTP 同步、用戶修改) |
System.nanoTime() | long (ns) | 納秒 (單調時鐘,高精度) | 效能基準測試、微基準、相對時間間隔測量 | 無絕對意義,僅相對差值有效;不可跨 JVM 比較 |
long start = System.currentTimeMillis();
// doSomething();
long end = System.currentTimeMillis();
System.out.println("耗時: " + (end - start) + " ms");
long start = System.nanoTime();
// doSomething();
long end = System.nanoTime();
System.out.println("耗時: " + (end - start) + " ns");
System.out.println("耗時: " + (end - start) / 1_000_000.0 + " ms");
手工測量存在 JIT 預熱、死碼消除、編譯器優化干擾等陷阱。**生產級微基準必須用 JMH** (OpenJDK 官方工具)。
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(2)
@State(Scope.Benchmark)
public class MyBenchmark {
@Benchmark
public void testMethod() {
// 被測代碼
}
}
org.openjdk.jmh:jmh-core + jmh-generator-annprocess。
// JUnit 4
@Test(timeout = 1000) // 超時失敗
public void test() { ... }
// JUnit 5 (Jupiter)
@Test
void test() {
Assertions.assertTimeout(Duration.ofMillis(500), () -> { ... });
}
僅適用於**超時保護**,不提供精確耗時統計。
currentTimeMillis() 測微秒級代碼:精度不足,結果多為 0 或波動極大。Blackhole.consume() (JMH) 或打印結果防止。nanoTime():不同 JVM 實例、不同機器的納秒基準無關聯性。currentTimeMillis() / Instant.now()。nanoTime() + 多次迭代取中位數。