- Home /
Time.deltaTime quite inaccurate
timer+=Time.deltaTime; I've always used everywhere. for simple timers of 1-60sec.
I'm aware of floating point issues with extensive use, but I recently found that doing this will get you an inaccuracy of .2 to .4 seconds for a 60 second period?!
I.e. Unity says 60 seconds have passed, in reality: 60.3 seconds have passed. ((version:2018.2.5f1)) Simple Update code to reproduce:
float t = 0;
double tt = 0; //more accurate bucket
System.Diagnostics.Stopwatch SW;
void Update() {
if (t == 0) {
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 60; //20 =.2 error, 200 =~.4s error
SW = new System.Diagnostics.Stopwatch();
SW.Start();
t = .00000001f; //negligible, don't count deltatime this frame, cause that was previous time.
} else {
t += Time.deltaTime;
tt += (double)Time.deltaTime;
}
if (t>60 && SW.IsRunning) {
SW.Stop();
Debug.Log("Float t="+t);
Debug.Log("Double tt=" + tt);
Debug.Log("StopWatch =" + SW.ElapsedMilliseconds/1000f);
}
}
This seems like a huge error for just blaming floating point accuracy.
With 60 FPS you have 3,600 frames in 60 seconds, and you get 0.2s error in these 60 seconds. So, the error per frame is 0.2 / 3,600 = 0.000056s.
Similarly, for 200FPS/0.4s error, the error per frame is 0.4 / 12,000 = 0.000033s.
So, the error per frame is in the order of about 4 hundredths of a millisecond, which is negligible for a game.
Answer by rossadamsm · Dec 16, 2018 at 08:20 AM
I am not sure exactly what causes the issue but I also get +- 0.2 seconds error with Update.
However if I use FixedUpdate the error is only about 0.003 seconds. So perhaps try that?
(Sorry I can't really explain why this is the case though.)
Answer by joedurb · Dec 17, 2018 at 05:04 AM
Additionally, Just a sanity check against normal base-line float accuracy:
float myDeltaTime = 1f / 53f;
float myTimeSum = 0;
for (int i = 0; i < 53 * 60; ++i) myTimeSum += myDeltaTime;
Debug.Log("60 seconds of time slices:" + myTimeSum);
That Simple addition of 53fps worth of time slices for 60 seconds= 59.998 vs Roughly 59.7 from unity.
Unity MUST not be giving a complete and total accounting of time since previous frame? I wonder if editor time is being lost or some such. I guess that would be the next check, try a build to see if time still not adding up.
@rossadamsm: The fixed update has equivalent accuracy to the direct addition i'm doing, which makes sense, since it's a simpler constant metric of 1/20f . Thanks for checking it :)