看来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");
}
}
Run Code Online (Sandbox Code Playgroud)
结果是(在Windows XP上):
The time interval of your OS: 15ms
Run Code Online (Sandbox Code Playgroud)
为什么不1ms呢?如何获得当前时间的精确毫秒?
这完全是预期的.你会在.NET上看到同样的东西DateTime.Now.(请参阅Eric Lippert 关于同一主题的面向.NET的视图主题的博客文章.)
您可以使用System.nanoTime()更准确的计时器进行测量 - 这并不意味着给出绝对时间,它仅用于测量间隔.
我不知道如何从Java或Win32获得更准确的绝对时间.说实话,系统时钟究竟有多准确?即使定期与NTP服务器同步,我也希望至少有几毫秒的不准确性.
基本上,如果你真的准确地依靠绝对时间,你应该改变你的设计.