0
\$\begingroup\$

I'm trying to calculate deltaTime, but it's not correct.

What's wrong in my code?

//declared outside
private long timeSinceStart = System.nanoTime() / 1000;
private long oldTimeSinceStart = 0;
public static long deltaTime = 1;

while(running)
  timeSinceStart = System.nanoTime() / 1000;
  deltaTime = timeSinceStart - oldTimeSinceStart;
  oldTimeSinceStart = timeSinceStart;
\$\endgroup\$
5
\$\begingroup\$

System.nanoTime() returns the time in nanoseconds.

In order to get it in milliseconds, do System.nanoTime() / 1000000.

Here is an example how to calculate delta time properly.

long last_time = System.nanoTime();

while(running) {
    long time = System.nanoTime();
    int delta_time = (int) ((time - last_time) / 1000000);
    last_time = time;
}
\$\endgroup\$
  • \$\begingroup\$ Your correct code is fixing MORE than your text explains. Because the real problem with OPs original code was that he NEVER was saving the start-time (overwriting it every loop). The actual fix isn't the /1000 or so, its NOT overwriting last_time anymore \$\endgroup\$ – Hobbamok Jun 5 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.