15

我正在尝试使用以下代码System.nanoTime()来测量代码的经过时间。

public static void main(String[] args) throws Exception {
    while (true) {
        long start = System.nanoTime();
        for (int i = 0; i < 10000; i++)
            ;
        long end = System.nanoTime();
        long cost = end - start;
        if (cost < 0) {
            System.out.println("start: " + start + ", end: " + end + ", cost: " + cost);
        }
    }
}

我得到这样的结果:

start: 34571588742886, end: 34571585695366, cost: -3047520
start: 34571590239323, end: 34571586847711, cost: -3391612
start: 34571651240343, end: 34571648928369, cost: -2311974
start: 34571684937094, end: 34571681543134, cost: -3393960
start: 34571791867954, end: 34571788878081, cost: -2989873
start: 34571838733068, end: 34571835464021, cost: -3269047
start: 34571869993665, end: 34571866950949, cost: -3042716
start: 34571963747021, end: 34571960656216, cost: -3090805
start: 34571965020545, end: 34571961637608, cost: -3382937
start: 34572010616580, end: 34572007613257, cost: -3003323

为什么我得到负值?

(操作系统:windows xp sp3,java:jdk1.6u27)

4

1 回答 1

16

nanoTime 可以取 CPU 时钟周期计数器。由于不同 CPU 的启动时间可能略有不同,因此不同 CPU 上的时钟计数器可能不同。Linux 对此进行了纠正,但旧版本的 Windows 没有。(我假设您有两个相隔 3 毫秒启动的 CPU)

您还应该偶尔看到超过 2.5 毫秒的正跳变。

尝试

if (cost < 0 || cost > 2000000) {

当进程在 CPU 之间切换时,您应该会看到一些向前跳跃和一些向后跳跃。

于 2011-10-23T13:11:00.027 回答