在Java中可以通过System.currentTimeMillis()或者System.nanoTime() (JDK>=5.0) 方法获得当前的时间的精确值。但是通过阅读Javadoc,我们发现这两个方法并不一定保证得到你所期望的精度。先来看System.currentTimeMillis():
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
诚如上面所说返回值的粒度依赖于底层操作系统,那么它在不同的平台上到底能提供是么样的精度,是否像函数名所写的那样真正 精 确到1毫秒呢?看下面一段测试程序:
public class ClockAccuracyTest {
public static void main(String args[]) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss:SSS");
int size = 4000000;
// create an array to hold millisecond times
// and loop to capture them
long times[] = new long[size];
for (int i = 0; i < size; i++) {
times[i] = System.currentTimeMillis();
}
// now display the unique times
long ti

本文通过测试分析了Java中System.currentTimeMillis()方法在Windows XP SP3上的精度问题,发现其粒度为15~16毫秒。而System.nanoTime()方法虽然提供了纳秒级精度,但不保证准确度。在Windows上,通过System.nanoTime()除以1000000L可以实现毫秒级别的精确计时。测试结果显示,这种方法能够达到1毫秒的精度。
最低0.47元/天 解锁文章
3712

被折叠的 条评论
为什么被折叠?



