1

It seems System.currentTimeMillis is not very accurate.

See this sample:

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

The result is (on Windows XP):

The time interval of your OS: 15ms

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

Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

8

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.)

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.

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Why in 2012 is it not possible to get an accurate time out of windows. I log things with ms times so I can see how long things take to run. I need to see if some things take 2ms vs 7ms so I can do tuning, but it's completely impossible in windows. Does anybody else think this is insane? (I'm a unix weenie and I've never had this problem before.) – stu Nov 19 '12 at 14:33
  • @stu: Simply put, you shouldn't be using a wall clock as a stopwatch. A wall clock is meant to give you a good representation of the current time; it's not designed for measuring small differences in time. That's precisely what nanoTime is for. – Jon Skeet Nov 19 '12 at 14:35
2

Yes. The javadoc for System.currentTimeMillis() says it:

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.

You could use System.nanoTime(), but make sure to read its javadoc to understand its limitations.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

It is not possible to get any more accurate with java on windows.

Brett Walker
  • 3,566
  • 1
  • 18
  • 36