Hi !
Featured games (90)
games approved by the League of Dukes
Games in Showcase (710)
Games in Android Showcase (212)
games submitted by our members
Games in WIP (785)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Thread.sleep() Inaccuracy  (Read 1585 times)
0 Members and 1 Guest are viewing this topic.
Offline cheloc

Innocent Bystander

« Posted 2012-11-05 21:56:52 »


I recently started developing games in Java. But I cant get pass one problem. I searched the web and didnt find any answer, so I entered this forums.

My problem is the following: Thread.sleep(time) is not being as good as it should be. Here some example:

   public static void main(String[] args) {
      while (true){

   private static void sleep(int i) {
      long startingtime = System.nanoTime();
      try {Thread.sleep(i);}
      catch (InterruptedException e) {e.printStackTrace();}
      long endingtime = System.nanoTime();
      double slepttime = (endingtime - startingtime ) /1000000.0;
      System.out.println("Expected: "+i+" Real: "+slepttime);

On my Windows7 Pc I get results like:
Expected: 20 Real: 19.929772
Expected: 20 Real: 19.881132
Expected: 20 Real: 19.908117
Expected: 20 Real: 19.919111
Expected: 20 Real: 19.911116
Expected: 20 Real: 19.899788
Expected: 20 Real: 19.889128
Expected: 20 Real: 19.906784

But on WindowsXP Pc's these results are really bad.

Expected: 20 Real: 18,7034
Expected: 20 Real: 29.2780
Expected: 20 Real: 26.14
Expected: 20 Real: 20.1889
Expected: 20 Real: 27.4749
Expected: 20 Real: 16.6664

My question is: whats the method you guys use to make gameloop wait? Because Thread.sleep() doesn't seem to be a really good way.


Offline RobinB

JGO Ninja

Medals: 44
Projects: 1
Exp: 3 years

Spacegame in progress

« Reply #1 - Posted 2012-11-05 22:19:27 »

THis is the way to do it really.
You need to compensate the sleep errors with code.

You could try extracting or adding the oversleep time to the sleep time of the next frame.
Offline Damocles
« Reply #2 - Posted 2012-11-05 22:26:22 »

You can also "burn off" cycles.
Using a while loop with Many Thread.yield , checking every run if you have burned off enough time yet.
Continue with execution when you have reached the threshold

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Danny02
« Reply #3 - Posted 2012-11-05 22:29:55 »

I just don't make my game loop wait^^
I really don't get why so many people around here use some trickery to get around 60 frames per second, there is no need for that even for fixed time steps.
One always hears about games running 60 fps, but I think most don't get that this has something to do with vsync(monitor refresh rate). And this has to be activated with OpenGL, which will then automaticly get your rendering down to 60fps(in most cases). So If you want a framerate of 60Hz just enable Vsync.

If you are using software rendering(i.e. Java2D), which doesn't support vsync and you don't want to run at full speed(to save energy of a smartphone for example), just place some "random" Thread sleeps in there.

Your construct to run your logic at fixed time steps shouldn't depend on thread sleep calls, because they can be quite inaccurate like you noticed.

How does something like this look?
long startTime = System.currentmilliseconds();
long elapsedTicks;
int ticksPerSecond = 40;
int timePerTick = 1000 / ticksPerSecond ;
   long time = System.currentmilliseconds();
   int newTicks = (time - startTime) / timePerTick - elapsedTicks;

   for(int i=0; i < newTicks; ++i)

   elapsedTicks += newTicks;

   //here you could put some code that if the framerate is going to high you put in some thread sleeps
Offline StumpyStrust
« Reply #4 - Posted 2012-11-05 22:39:10 »

Yes a busy loop works very well but just letting things go on and on is bad as you use too much cpu when you don't need to. Think of mobile devices with power consumption.

If you use lwjgl then there is a very nice convenience method there to sync stuff.
There are also so very nice game loop tutorials here if anyone wants to try the search engine.

Offline Cero
« Reply #5 - Posted 2012-11-05 23:05:45 »

I just like to say that no-fps cap has not only to do with power comsuption and mobile devices. apart form delta programming being awful, I will delete every game that runs max FPS immediately.
It will heat up the GPU for no reason and put stress on the system.

I have a open case, and I can actually HEAR the GPU getting overstressed if you do that; its like a high pitched quiet beep.

Also fixed framerate ftw.

Offline ra4king

JGO Kernel

Medals: 471
Projects: 3
Exp: 5 years

I'm the King!

« Reply #6 - Posted 2012-11-06 02:12:06 »

Windows has a *very* inaccurate sleep timer, which is why you are noticing those terrible timings. Check out my game loop along with a very accurate sleep trick.

Offline Varkas
« Reply #7 - Posted 2012-11-06 11:45:45 »

Yes a busy loop works very well but just letting things go on and on is bad as you use too much cpu when you don't need to. Think of mobile devices with power consumption.

I tried to combine an underestimed sleep with a busy loop to wait the last few ms precisely. I.e. I used a sleep with 5ms less than the total sleep time, and waited the remaining time in a busy loop. That was quiet precise and somewhat multi-process friendly.

if (error) throw new Brick(); // Blog (german):
Offline matheus23

JGO Kernel

Medals: 138
Projects: 3

You think about my Avatar right now!

« Reply #8 - Posted 2012-11-06 14:55:02 »

Yes, I don't like games running on max FPS too, because my cpu or graphics chip could get really hot, and this reduces the life time of them.

Anyways: Here is my implementation, which is not as simple as ra4king's implementation, but with Listeners and with Rivens super-duper accurate Sleep syncing. It's hosted on GitHub and needs only the files in the "org.matheusdev.util.gameloop" package. See the package here:

It allows you different techneques:
  • A "frame-skipper", which skips rendering, if there is enough time left, since it would only be redunant rendering time (but this version consumes 100% cpu),
  • a delta-based rendering loop, which only renders and ticks your game as much as needed and even handles the computation of the delta-time, which is simply a double, which is 1, when you currently render at 60 fps, and lower, if the framerate is higher, or higher, if the framerate is lower. For example, in case your game renders at 120 fps, the delta would be 0.5. Also, it is flexible, which means it updates every frame.
  • And the last techneque is a "no-tech", which does just no frame skipping, and no sleeping at all. It just renders at highest framerate.

And at the very last: All versions include an accurate FPS counter, which is just given to you as an int.

See my:
    My development Blog:     | Or look at my RPG | Or simply my coding
http://matheusdev.tumblr.comRuins of Revenge  |      On Github
Pages: [1]
  ignore  |  Print  
You cannot reply to this message, because it is very, very old.

numerical (122 views)
2017-02-21 07:32:16

numerical (121 views)
2017-02-21 07:31:46

theagentd (228 views)
2017-02-18 13:42:33

theagentd (229 views)
2017-02-18 13:35:16

h.pernpeintner (1392 views)
2017-01-24 22:39:11

h.pernpeintner (1380 views)
2017-01-24 22:38:32

Galdo (1942 views)
2017-01-12 13:44:09

Archive (2011 views)
2017-01-02 05:31:41

0AndrewShepherd0 (2548 views)
2016-12-16 03:58:39

0AndrewShepherd0 (2318 views)
2016-12-15 21:50:57
List of Learning Resources
by elect
2016-09-09 09:47:55

List of Learning Resources
by elect
2016-09-08 09:47:20

List of Learning Resources
by elect
2016-09-08 09:46:51

List of Learning Resources
by elect
2016-09-08 09:46:27

List of Learning Resources
by elect
2016-09-08 09:45:41

List of Learning Resources
by elect
2016-09-08 08:39:20

List of Learning Resources
by elect
2016-09-08 08:38:19

Rendering resources
by Roquen
2016-08-08 05:55:21 is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!