Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 677
perseverance Avatar asked Nov 14 '12 00:11

perseverance


People also ask

Can you console log in Rails?

One of the best tools in a rails developers arsenal is the rails console, being extremely useful for brainstorming, debugging, and testing. Having it log active record queries directly to the console can improve readability and convenience over looking through the development logs to see what SQL queries have been run.

How do I run a Ruby script in Rails console?

Run source code from the editor in a console Open the required Ruby file in the editor (if necessary, select a fragment of code to be executed). From the main menu, choose Tools | Load file/selection into IRB/Rails console.

What can you do in Rails console?

The console command lets you interact with your Rails application from the command line. On the underside, bin/rails console uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.


2 Answers

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)
like image 177
pje Avatar answered Nov 15 '22 17:11

pje


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
like image 31
Igor Kasyanchuk Avatar answered Nov 15 '22 19:11

Igor Kasyanchuk