Loua
Loua

Reputation: 161

Fps algorithm error with systemtime

I'm having some trouble with an FPS algorithm I have tried to implement into my simulator. The general idea is that I want 60 to be the maximum amount of tick-render cycles per second. Here is my code:

public void run() {

    x = 0; //tick is set to 0 originally 
    lastT = System.currentTimeMillis(); //system time in milliseconds

    //tick-render cycle
    while(running == true){

        currentT = System.currentTimeMillis();
        deltaT += currentT - lastT;
        lastT = currentT;

        if(deltaT/tPerTick >= 1){
            tick(); 
            render();
            deltaT = 0; 
        }

    }

    stop(); //stops thread when running =! true
}

The constant 'tPerTick' is defined as follows

double tPerTick = 1000 / 60

Throughout my development of this program I thought that this algorithm was working perfectly, it was only when I traced this algorithm to confirm that I found an issue. Every time the loop cycles (iterates? I'm not sure what the correct word is here) the if statement is found to be true and therefore the tick-render cycle is executed. I did some more tracing (to find why this was happening) and found that the values for deltaT are always well over tPerTick, like way way over (in some cases 19 seconds even though this is clearly not the case). Is there an error somewhere in my code? I think that I must be either using System.currentTimeMillis() wrong or am tracing the algorithm incorrectly.

In the actual simulation it seems to be working fine (not sure why). When I draw the graphics I pass 'x' (the tick) in and write the time to the screen as x / 60 seconds.

Upvotes: 0

Views: 44

Answers (1)

Loua
Loua

Reputation: 161

Answering my own question.

System.currentTimeMillis();

Gets the current system time. If you are going through the algorithm manually in debug mode, 'deltaT' is going to be very large since it will be equal to the time that you take to manually trace through the algorithm.

Upvotes: 1

Related Questions