为什么我使用System.nanoTime()获得负时间? [英] Why I get a negative elapsed time using System.nanoTime()?

查看:1337
本文介绍了为什么我使用System.nanoTime()获得负时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码与 System.nanoTime()来衡量代码的已用时间。

I'm trying to use following code with System.nanoTime() to measure the elapsed time of code.

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);
        }
    }
}

我得到了这样的结果:

And I get such result:

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)

(OS: windows xp sp3, java: jdk1.6u27)

推荐答案

nanoTime可以取自CPU时钟周期计数器。由于不同的CPU可以在稍微不同的时间启动,因此不同CPU上的时钟计数器可以不同。 Linux纠正了这一点,但旧版本的Windows却没有。 (我假设你有两个相隔3毫秒启动的CPU)

The nanoTime can be taken of the CPU clock cycle counter. As different CPUs can be started at slightly different times, the clock counter can be different on different CPUs. Linux corrects for this, but older versions of Windows do not. (I assume you have two CPUs which were started 3 ms apart)

你还应该看到偶尔跳跃超过2.5毫秒。

You should also see positive jumps of over 2.5 ms occasionally.

尝试

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

当CPU在CPU之间切换时,您应该会看到一些跳转并且有些跳转。

And you should see some jump forward and some jump backward as the process is switched between CPUs.

这篇关于为什么我使用System.nanoTime()获得负时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆