How to measure function execution time in Ruby

1 Answer

0 votes
# Measuring function execution time in 
# Ruby using a reusable Timer (milliseconds + seconds)

# ---------------------------
# Reusable Timer class
# ---------------------------
class Timer
  def initialize
    @start = 0.0
    @end = 0.0
  end

  # Start the timer
  def start
    @start = Process.clock_gettime(Process::CLOCK_MONOTONIC) # high‑precision timer
  end

  # Stop the timer
  def stop
    @end = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  end

  # Return elapsed time in milliseconds
  def elapsed_milliseconds
    (@end - @start) * 1000.0
  end

  # Return elapsed time in seconds
  def elapsed_seconds
    @end - @start
  end
end

# ---------------------------
# Function to measure
# ---------------------------
def work
  sum = 0
  100_000_000.times { |i| sum += i }
end

# ---------------------------
# Main program
# ---------------------------
t = Timer.new

t.start
work
t.stop

ms  = t.elapsed_milliseconds
sec = t.elapsed_seconds

puts "Execution time: #{ms} ms"
puts "Execution time: #{sec} seconds"



=begin

run:

Execution time: 5167.134837014601 ms
Execution time: 5.167134837014601 seconds

=end

 



answered 2 hours ago by avibootz
...