Search code examples
crystal-lang

Subtract two times in crystal lang


I am writing a small benchmark for crystal, and want to compare the time taken without any other library.

In programming language like ruby I would do this:

t = Time.new
sleep 3
puts "Time: #{Time.new - t}s"

Is there a way to get current monotonic clock time and subtract it from another time to get accuracy up to at least 3 decimal places?


Solution

  • The typical time representation provided by the operating system is based on a "wall clock" which is subject to changes for clock synchronization. This can result in discontinuous jumps in the time-line making it not suitable for accurately measuring elapsed time.

    ...

    As an alternative, the operating system also provides a monotonic clock. Its time-line has no specfied starting point but is strictly linearly increasing.

    This monotonic clock should always be used for measuring elapsed time.

    A reading from this clock can be taken using .monotonic:

    t1 = Time.monotonic
    # operation that takes 1 minute
    t2 = Time.monotonic
    t2 - t1 # => 1.minute (approximately)
    

    The execution time of a block can be measured using .measure:

    elapsed_time = Time.measure do
      # operation that takes 20 milliseconds
    end
    elapsed_time # => 20.milliseconds (approximately)
    

    -- Time - github.com/crystal-lang/crystal

    * Emphasis mine.

    So your example would be basically the same, but with Time.monotonic instead of Time.new.