Is there a way to check the performance of a command in the console in Ruby on Rails?

3.9k Views Asked by At

I couldn't find any information on if this was possible but it would be useful I could call a method on a command in the rails console and determine the performance using any measurement but I was mostly thinking about in time.

For example, I'm trying to figure out which of these is faster:

[val2,val3,val4,val5,val6].find{|x| x != val1}
[val2,val3,val4,val5,val6].all?{|x| x == val1} 

Is there something like this?

[val2,val3,val4,val5,val6].find{|x| x != val1}.performance
2

There are 2 best solutions below

3
pje On BEST ANSWER

There is! And you don't even need Rails. Look into benchmark from the standard library.

As a sample:

require 'benchmark'

puts Benchmark.measure { [val2,val3,val4,val5,val6].find{|x| x != val1} }
puts Benchmark.measure { [val2,val3,val4,val5,val6].all?{|x| x == val1} }

The report that is output will show (in seconds):

  • User CPU time.
  • System CPU time.
  • Sum of the User and System CPU times.
  • The elapsed real time.

Something that looks like this:

0.350000   0.010000   0.360000 (  0.436450)
0
Igor Kasyanchuk On

This gem: https://github.com/igorkasyanchuk/benchmark_methods

No more code like this:

t = Time.now
user.calculate_report
puts Time.now - t

Now you can do:

benchmark :calculate_report # in class

And just call your method

user.calculate_report