# How to accurately count 1 second within my logic update?

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?

• time += 1000000000; instead of time = system.nanoTime(); else you are skipping a few milliseconds each time. – API-Beast Mar 12 '14 at 0:43
• 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 – Roy T. Mar 12 '14 at 13:26

• 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. – Elva Mar 12 '14 at 9:22