Hi all,
I knocked up a simple frame rate capping class this evening to make my life easier - I was fiddling with a few things, and my animations were running at different speeds depending on the amount of work done that frame. Lock the frame rate to 60 FPS and I can be sure that things will run at no more than that rate.
This is a very simple bit of code, and is a first cut. It works fine, but needs a few more features. Cas mentioned the process in his diary a while back, and I’ve just found need for it.
I’d be grateful if anyone interested in it give it a go and tell me if it works for you. Consider it BSD licenced! Here’s the new class:
import org.lwjgl.Sys ;
public class FrameRateCap
{
private FrameRateCap() {}
private static int frameRate = -1 ;
private static long preferredFrameTicks ;
private static long frames ;
private static long startTick ;
private static long endTick ;
private static long frameStartTick ;
public static void setFrameRate(int frameRate2)
{
assert (frameRate2 > 0) : frameRate2 ;
assert (frameRate == -1) : "Already set" ;
frameRate = frameRate2 ;
preferredFrameTicks = Sys.getTimerResolution() / frameRate ;
}
public static void start()
{
startTick = Sys.getTime() ;
frames = 0 ;
}
public static void startFrame()
{
frameStartTick = Sys.getTime() ;
}
public static void endFrame()
{
frames++ ;
long frameDurationTicks = Sys.getTime() - frameStartTick ;
while(frameDurationTicks < preferredFrameTicks)
{
long sleepTime = ((preferredFrameTicks - frameDurationTicks) * 1000) / Sys.getTimerResolution() ;
try
{
Thread.sleep(sleepTime) ;
}
catch(InterruptedException e)
{
}
frameDurationTicks = Sys.getTime() - frameStartTick ;
}
}
public static void end()
{
endTick = Sys.getTime() ;
}
public static long getFrames()
{
return frames ;
}
public static float getFramesPerSecond()
{
return frames / ((endTick - startTick) / (float)Sys.getTimerResolution()) ;
}
}
And you use it like this:
FrameRateCap.setFrameRate(60) ;
FrameRateCap.start() ;
while(!finished)
{
FrameRateCap.startFrame() ;
// Drawing code here
FrameRateCap.endFrame() ;
}
FrameRateCap.end() ;
System.out.println("Frames rendered: " + FrameRateCap.getFrames()) ;
System.out.println("FPS: " + FrameRateCap.getFramesPerSecond()) ;
You just tell it how many FPS you want, tell it when the drawing process starts and ends, and tell it about the start and end of each frame, and it’ll introduce a padding delay if the drawing completed early and track number of frames rendered and actual frames per second for you.
Any comments?

