The Crystal Programming Language Forum

Am I getting the delta time correctly?

https://play.crystal-lang.org/#/r/7sc0/edit

last_update = Time.local.to_unix_ms
tick_rate = 1/15

i = 0
loop do
  break if i == 25 # we do this so the playground doesn't break
  i+=1
    
  delta = Time.local.to_unix_ms - last_update
  
    puts "#{delta/1000}, #{tick_rate}"
  last_update = Time.local.to_unix_ms
  sleep tick_rate
end


I’m curious if this is the proper way to obtain a delta time in Crystal.

It’s better to use Time.monotonic

https://crystal-lang.org/api/0.31.1/Time.html#monotonic:Time::Span-class-method

There is also a Time.measure which takes a block and measures elapsed time

https://crystal-lang.org/api/0.31.1/Time.html#measure(&block):Time::Span-class-method

1 Like

Thanks @vlazar! I just looked into monotonic, had to do a bit more research into that word, lol. I think I understand it better now. Stumbled upon this thread https://stackoverflow.com/a/3527632, so I assume it’s more of a accurate representation of an elapsed time?

From link you posted

The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings

With non monotonic time if you do

start = Time.local.to_unix_ms
# some code to run
elapsed = Time.local.to_unix_ms - start

You can get inacurate and negative elapsed time which is I assume not what you would want at all.

The most common usecase here is an NTP client. Most of the daemons try to converge the clock by minimal increments, but most of the users tend to want the clock synchronized right now, and if you are unlucky you’ll get the first measurement before the clock change and the second one after. Monotonic clock is a separate time source that’s not affected so you’ll be okay in any case.

i once had a virtual server stuck in a time loop. you would not believe how long it took me to find the cause for the bag of unrelated and incredibly weird things that happen when your server keeps reliving the same 8 second interval.

1 Like