← 中文资源

简体中文版本

nanoTime 测量经过时长

System.nanoTime 的起点是任意的,唯一有效用法是两次调用相减取差值;挂钟可能被系统回调,测耗时永远用 nanoTime 差值而不是日期差。

阅读英文原文

实现说明

真正干活的是类 ElapsedProbe和函数 timeConcat、timeBuilder、main,其余都是接线。 本示例的循环部分是 for (int i = 0; i < rounds; i++)。

使用要点

  • 演示输出是带标签的(concat :、builder :、builder wins:),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 timeConcat、timeBuilder。

常见问题

运行「nanoTime 测量经过时长」会打印什么?

整个文件跑完,输出行以 concat :、builder :、builder wins: 这类前缀开头。

签名一览:static long timeConcat(int rounds)

核心语句

return System.nanoTime() - start;

代码示例

public class ElapsedProbe {

    static long timeConcat(int rounds) {
        long start = System.nanoTime(); // 原点任意:只能相减比较差值
        String acc = "";
        for (int i = 0; i < rounds; i++) {
            acc += i;
        }
        return System.nanoTime() - start;
    }

    static long timeBuilder(int rounds) {
        long start = System.nanoTime();
        var sb = new StringBuilder();
        for (int i = 0; i < rounds; i++) {
            sb.append(i);
        }
        return System.nanoTime() - start;
    }

    public static void main(String[] args) {
        long concatNs = timeConcat(2000);
        long builderNs = timeBuilder(2000);
        System.out.println("concat  : " + concatNs / 1_000_000 + " ms");
        System.out.println("builder : " + builderNs / 1_000_000 + " ms");
        System.out.println("builder wins: " + (builderNs < concatNs));
    }
}