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
 
n350071 profile image
n350071🇯🇵 •

I've found a better way

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