Godot Version
4.4
Question
I noticed today that timers have extremely inconsistent behavior - specifically during the first second or so of the project running. I use this method in my Lib
singleton to handle delays as a multiple of the global Lib.time
:
func sleep(ticks: float = 1.0) -> void:
var start = Time.get_ticks_msec()
await get_tree().create_timer(ticks * self.time).timeout
var end = Time.get_ticks_msec()
print("Expected time elapsed: %s, actual time elapsed: %s seconds" % [ticks * self.time, ((end - start) / 1000.0)])
The timing and print behavior is just there for debugging of course, usually it’s just the second line. Lib.time
is 0.8 by default, changed to 0.3 for certain unit tests. In said unit test, when I run for i in range(10): await Lib.sleep()
, I get the following output:
Expected time elapsed: 0.3, actual time elapsed: 0.066 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.297 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.305 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.301 seconds
Expected time elapsed: 0.3, actual time elapsed: 0.303 seconds
This behavior is very consistent; every time I run it the first delay is ~0.06-0.08 seconds, and every subsequent delay is 0.3 +/- 0.005 seconds. I also tried running the same loop in my main code instead of in unit testing; in this case Lib.time
was set to 0.8, the first delay was ~0.65 seconds, and every subsequent delay was 0.8 +/- 0.01 seconds. The minor variations are not a problem but being off by 0.2 seconds is a major problem. Why do timers do this?