How do I get elapsed time in milliseconds in Ruby?

前端 未结 10 2126
走了就别回头了
走了就别回头了 2020-12-13 05:27

If I have a Time object got from :

Time.now

and later I instantiate another object with that same line, how can I see how many

相关标签:
10条回答
  • 2020-12-13 06:04

    You can add a little syntax sugar to the above solution with the following:

    class Time
      def to_ms
        (self.to_f * 1000.0).to_i
      end
    end
    
    start_time = Time.now
    sleep(3)
    end_time = Time.now
    elapsed_time = end_time.to_ms - start_time.to_ms  # => 3004
    
    0 讨论(0)
  • 2020-12-13 06:04

    I think the answer is incorrectly chosen, that method gives seconds, not milliseconds.

    t = Time.now.t­o_f
    => 1382471965.146
    

    Here I suppose the floating value are the milliseconds

    0 讨论(0)
  • 2020-12-13 06:05

    %L gives milliseconds in ruby

    require 'time'
    puts Time.now.strftime("%Y-%m-%dT%H:%M:%S.%L")
    

    or

    puts Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")
    

    will give you current timestamp in milliseconds.

    0 讨论(0)
  • The answer is something like:

    t_start = Time.now
    # time-consuming operation
    t_end = Time.now
    
    milliseconds = (t_start - t_end) * 1000.0
    

    However, the Time.now approach risks to be inaccurate. I found this post by Luca Guidi:

    https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/

    system clock is constantly floating and it doesn't move only forwards. If your calculation of elapsed time is based on it, you're very likely to run into calculation errors or even outages.

    So, it is recommended to use Process.clock_gettime instead. Something like:

    def measure_time
      start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      yield
      end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      elapsed_time = end_time - start_time
      elapsed_time.round(3)
    end
    

    Example:

    elapsed = measure_time do
        # your time-consuming task here:
        sleep 2.2321
    end
    
    => 2.232
    
    0 讨论(0)
提交回复
热议问题