System.currentTimeMillis()在Windows XP上不准确? [英] System.currentTimeMillis() is not accurate on windows XP?

查看:265
本文介绍了System.currentTimeMillis()在Windows XP上不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 System.currentTimeMillis 不是很准确。

参见此示例:

public class MillisTime {
    public static void main(String[] args) {
        long start = 0;
        long end = 0;
        while (true) {
            if (start == 0) {
                start = System.currentTimeMillis();
            } else {
                long current = System.currentTimeMillis();
                if (current != start) {
                    end = current;
                    break;
                }
            }
        }
        System.out.println("The time interval of your OS: " + (end - start) + "ms");
    }
}

结果是(在Windows XP上):

The result is (on Windows XP):

The time interval of your OS: 15ms

为什么它不是 1ms ?如何获得当前时间的精确毫秒?

Why it's not 1ms? And how to get accurate millis second of current time?

推荐答案

这完全是预期的。你会在.NET上看到使用 DateTime.Now 的相同内容。 (参见Eric Lippert的博客关于同一主题的面向.NET的视图的主题。)

This is entirely expected. You'd see the same thing on .NET using DateTime.Now. (See Eric Lippert's blog post on the topic for a .NET-oriented view on this same topic.)

您可以使用 System.nanoTime() 获得更准确的计时器仅用于测量 - 这并不意味着提供绝对时间,它仅用于测量间隔

You can use System.nanoTime() to get a more accurate timer for measurements only - that's not meant to give an absolute time, it's only for measuring intervals.

我不知道如何从Java或Win32获得更准确的绝对时间。说实话,系统时钟究竟有多精确?即使定期与NTP服务器同步,我也希望至少有几毫秒的不准确度。

I don't know of any way to get a more accurate absolute time, either from Java or from Win32. To be honest, how accurate is the system clock going to be anyway? Even with regular syncing with an NTP server I'd expect at least a few milliseconds inaccuracy.

基本上,如果你真的准确地依靠绝对时间,那么你应该改变你的设计。

Basically, if you're relying on getting an absolute time really accurately, you should probably change your design.

这篇关于System.currentTimeMillis()在Windows XP上不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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