problem with calculation frames per second

Hi,

I am practising a little bit now by making a pac-man game in Java2D. Everything is working pretty well except calculating the frames per second.

This is my run() method which continuously calls the gameloop update(Graphics2D gfx) Here you can see my futile attempt at calculating the FPS

public void run() {
while (isRunning) {
long starttime = System.currentTimeMillis();
try {
Graphics2D gfx = (Graphics2D)getGraphics();
update(gfx);
Thread.currentThread().sleep(25);

        }
        catch (InterruptedException ex) {
            System.out.println("Something went seriously wrong!");
        }
        long duration = System.currentTimeMillis() - starttime;
        double fps = 1/(duration*0.001);
        System.out.println("FPS: " + fps);
    }
}

To me it seems this should work, however, with a sleep of 25 milliseconds, the fastest FPS I should be able to get is 40 fps
The strange thing is, my FPS keeps on flipping between 31.5 and 61.2 fps when I make the sleep longer, like 50, it will switch between 15.8 and 16.1 continuously.
If I put the sleep on 1 ms, it still switches between 31.5 and 61.2 when I take out the update(gfx) it will also switch to INF next to the 31.5 and 61.2

What am I doing wrong here? Or does anyone have a way of doing this correctly?

Thread.sleep(x); is very inaccurate, depending on the OS

[x] WinXP might have a resolution of 10ms
[x] Linux might have a resolution of 1ms
[x] Win98 might have a resolution of 55ms

thanx for the answer, but then what do I do? can i just leave the sleep out of it? I read somewhere that if I do that the program will crash.

Get a start-time. (startTime = System.nano… for example)

in your drawing loop:

if (currentTime - startTime) >= 1 second {
display or update the (fps) on screen;
startTime = currentTime;
fps = 0;
}
do your drawing.
Thread.yield();
fps++;

And be sure to let your sprite calculations be time-based, not frame-based.