Java scheduled executor accuracy

大兔子大兔子 提交于 2019-12-03 11:52:51

The scheduled executor service uses System.nanoTime which doesn't drift as much as currentTimeMillis. Except if you are running on an XP system with more than one CPU socket. There is a bug in XP where the OS call System.nanoTime() uses is not consistent between sockets so as the thread switches which socket it is running on, you can expect to see this jumping around. (This is not a problem on Vista/7)

On a Linux system with one socket your program reports 0 - 3 ms drift.

Try this program.

public static void main(String... args) throws Exception {
    long start = System.nanoTime();
    long time = start;
    while(time < start + 3e10) {
        long now = System.nanoTime();
        if (now < time || now > time + 50000) {
            System.out.println(now - time);
            now = System.nanoTime();
        }
        time = now;
    }
}

On an i7 system I see approx 10 jumps of up to 2 ms. If I use the machine I see more. What I expect you might see is large negative and positive timings.

Seems normal to me, it varies in the range of 5000/2. In stead of format + println you should try a fast logging, so the overhead drift of println is not measured. Would be interesting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!