DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

Ruby Instant performance measurement

πŸ”— Parent Note

πŸ€” Situation

Let's suppose that you have like this code and you want to compare the performances of instance and session.

def current_role
  return @current_role if @current_role
  # ommit..
  @current_role = session[CURRENT_ROLE].reload
end

πŸ¦„ Instant Solution

You can measure by this code.

def instant_performance(&target)
  start_time = Time.now
  yield
  Time.now - start_time
end

πŸ‘ Usage & examples

> instant_performance{ puts 'hello' }
hello
=> 3.9e-05

> instant_performance{ puts 'hello' }.class
hello
=> Float

> instant_performance{ @user }
=> 2.0e-06

> instant_performance{ @current_role }
=> 3.0e-06

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 41.0

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> Infinity

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 44.0

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 42.0

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 29.0

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 56.0

> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }

=> Infinity
> instant_performance{ user_session[CURRENT_ROLE] } / instant_performance{ @current_role }
=> 50.00000000000001
``

Top comments (2)

Collapse
 
ohaddahan profile image
ohaddahan • Edited

This is a good naive way but there are many proper tools developed for this with better accuracy and performance.

github.com/evanphx/benchmark-ips is a great tool and should be used for benchmarks.
Also, Time.now is slower and less accurate compared to

Process.clock_gettime(Process::CLOCK_MONOTONIC)

require 'benchmark/ips'
Benchmark.ips do |x|
  x.config(:time => 5, :warmup => 2)
  x.report("Time.now") do
    Time.now
  end
  x.report("Process.clock_gettime(Process::CLOCK_MONOTONIC)") do
    Process.clock_gettime(Process::CLOCK_MONOTONIC)
  end
end


Warming up --------------------------------------
            Time.now   151.525k i/100ms
Process.clock_gettime(Process::CLOCK_MONOTONIC)
                       245.057k i/100ms
Calculating -------------------------------------
            Time.now      2.383M (Β± 6.2%) i/s -     11.970M in   5.045105s
Process.clock_gettime(Process::CLOCK_MONOTONIC)
                          5.875M (Β± 2.6%) i/s -     29.407M in   5.009710s


Collapse
 
n350071 profile image
n350071πŸ‡―πŸ‡΅

I've found a better way

require 'benchmark'
result = Benchmark.realtime do
  # your code
end
puts "time: #{result} sec"