Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (568)
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 933 times)
0 Members and 1 Guest are viewing this topic.
Offline cheloc

Innocent Bystander





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

Hello,

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:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
   public static void main(String[] args) {
      while (true){
         sleep(20);
      }
     
   }

   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.
Ej:

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.

Thanks!


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?
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
long startTime = System.currentmilliseconds();
long elapsedTicks;
int ticksPerSecond = 40;
int timePerTick = 1000 / ticksPerSecond ;
while(running)
{
   long time = System.currentmilliseconds();
   int newTicks = (time - startTime) / timePerTick - elapsedTicks;

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

   elapsedTicks += newTicks;
   
   render();

   //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: 347
Projects: 3
Exp: 5 years


I'm the King!


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

@OP
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): http://gedankenweber.wordpress.com
Offline matheus23

JGO Kernel


Medals: 108
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: https://github.com/matheus23/Utils/tree/master/Utils/src/org/matheusdev/util/gameloop

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.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (39 views)
2014-09-24 16:13:29

Pippogeek (30 views)
2014-09-24 16:12:22

Pippogeek (20 views)
2014-09-24 16:12:06

Grunnt (46 views)
2014-09-23 14:38:19

radar3301 (28 views)
2014-09-21 23:33:17

BurntPizza (64 views)
2014-09-21 02:42:18

BurntPizza (36 views)
2014-09-21 01:30:30

moogie (42 views)
2014-09-21 00:26:15

UprightPath (52 views)
2014-09-20 20:14:06

BurntPizza (54 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org 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‑gaming.org
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!