Java System System.currentTimeMillis(); error

Today using LWJGL(not sure maybe problem only with him)
I find error


Thread.sleep(10); // sometimes after call sleep
System.currentTimeMillis();// milis returns same as before sleep
//Nano sec return right value

I use this code to synchronize physics tic


		long time = System.currentTimeMillis();
		Frames_Dif_Milis = time - Frame_End_Milis;
		Frame_End_Milis = time;
      Thread.sleep(10);

But some times Frames_Dif_Milis == 0; Java 1.7
To fix error I use now nano sec difference :slight_smile:

That’s probably a Windos bug - as it is the only OS that doesnt return accurate milisecond timer. It rounds it to 16 miliseconds.

Your best bet is to use System.nanoTime(); which doesnt use that retarder windows pipeline underneath.


long time = System.nanoTime();

// do stuff

time = (System.nanoTime() - time) / 1000000; // here you go, accurate miliseconds

Ty i fix for nanosec :wink:

A more easier solution is to create a method [icode]getCurrentTime()[/icode] to convert the nanos into millis and return them. Here’s it.


public static long getCurrentTime()
{
    return System.nanoTime() / 1000000;
}

Then to synchronize physics, your snippet becomes


long time = getCurrentTime();
Frames_Dif_Milis = time - Frame_End_Milis;
Frame_End_Milis = time;
Thread.sleep(10);

Don’t forget to replace all calls to [icode]System.currentTimeMillis()[/icode] to [icode]MyGameUtil.getCurrentTime()[/icode]

I’ve read about the 16 ms accuracy on windows before, and I recently tested this in Win 7 64-bit. At least on that OS, I could not reproduce the claimed 16ms rounding. Even for a short sleep like 5ms, the currentTimeMillis() result only differed from nanoTime() by 1ms:

It might be that on Windows Vista/7 it is actually not relevant anymore, I never tested that. Its not really a “bug”, its just a piece of retarded legacy in the Win32 API that I believe goes all the way back to Windows 3.x. You can set the system-wide precision yourself with an API call, many applications which require high precision timing (video playback software, games) actually do that. On WindowsXP it is certainly still relevant, on some systems the precision may be 10ms and on others 15ms to make it even more difficult. So if you want your stuff to work properly on WindowsXP, better not ignore it.

You can test it out if you still have XP: activate a movie player (VLC or something) and while the movie is playing, run your Java application and check the sleep timing precision. You’ll find it is actually 1 or 2ms as if by magic, if the other software actually changes the precision of course.

Hi

You should look at this bug report:
http://bugs.sun.com/view_bug.do?bug_id=6435126

We already mentioned it here:

indeed and in LWJGL (and by extension LibGDX) the workaround fix is actually implemented, which is a very nice thing indeed :slight_smile: