I have the following method:

long time = system.nanoTime();

public void count(){

    if (System.nanoTime() > (time+1000000000)){

        //Output something or perform action here
        Log.v("timer","One second passed");

        //Reset for next second-count
        time = system.nanoTime();


This should output to the console every 1 second. It's close, but it seems not quite perfect.

If I time this with an actual stop watch (or with the same code running on another device), over time, it becomes slightly 'off'. Not by much, but it's off. After a minute, it's about 1/4 of a second off, the longer it is left, the larger the discrepancy.

The above method is called from within my updateLogic() method which is called aprox 60 times per second from my main game loop.

Can anyone tell me why this doesn't count extactly 1 second or why it's becoming out of snyc over time? How can I get a perfectly accurate timer that will run exactly the same on all devices?

  • 1
    \$\begingroup\$ time += 1000000000; instead of time = system.nanoTime(); else you are skipping a few milliseconds each time. \$\endgroup\$
    – API-Beast
    Mar 12, 2014 at 0:43
  • \$\begingroup\$ It looks like you're making a fixed time-step update loop. While this is generally a good idea getting it right is quite hard. Please see this article: gafferongames.com/game-physics/fix-your-timestep \$\endgroup\$
    – Roy T.
    Mar 12, 2014 at 13:26

1 Answer 1


Basically, your Log statement is taking up a few milliseconds, so what your code is actually doing looks sorta like this from a time perspective:

|---------1 sec------|-Log-|---------1 sec------|

As Mr. Beast said, you should use time += 1000000000;, not time = System.nanoTime();

  • 1
    \$\begingroup\$ Besides the time it takes to log, it is also possible that your game gets switched out by the OS for a while, if done at the wrong time (anywhere after the if but before the time = nanoTime() bit) it'll be off even more. \$\endgroup\$
    – Elva
    Mar 12, 2014 at 9:22
  • \$\begingroup\$ This. Thanks, I thought it would be something like time being skipped somewhere but I just couldn't figure out where or how it was happening - thanks also to @Mr. Beast for the initial comment \$\endgroup\$ Mar 12, 2014 at 13:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .