Skip to content

Instantly share code, notes, and snippets.

@huydx
Created February 16, 2013 16:24
Show Gist options
  • Save huydx/4967536 to your computer and use it in GitHub Desktop.
Save huydx/4967536 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'ruby-prof'
names = ["matz", "rossum", "ryal", "ritchie", "brendan"]
n = 5000
class Array
def method_missing name, *argv
super unless name =~ /^sort_by_(¥w+)_(asc|desc)$/
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1]
Array.class_eval <<-METHOD
def #{name}
sort #{condition}
end
METHOD
instance_eval "#{name}"
end
end
RubyProf.start
n.times { names.sort_by_length_asc }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
Array.send :remove_method, :sort_by_length_asc
class Array
def method_missing name, *argv
super unless name =~ /^sort_by_(¥w+)_(asc|desc)$/
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1]
instance_eval "sort #{condition}"
end
end
RubyProf.start
n.times { names.sort_by_length_asc }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
@huydx
Copy link
Author

huydx commented Feb 19, 2013

Thread ID: 2151954760
Total: 0.150838
Sort by: self_time

%self total self wait child calls name
56.69 0.121 0.086 0.000 0.035 5000 Array#sort
23.53 0.035 0.035 0.000 0.000 30000 Fixnum#<=>
11.40 0.138 0.017 0.000 0.121 5000 Array#sort_by_length_asc
8.25 0.151 0.012 0.000 0.138 1 Integer#times
0.04 0.151 0.000 0.000 0.151 1 Global#[No method]
0.03 0.000 0.000 0.000 0.000 1 Module#class_eval
0.02 0.000 0.000 0.000 0.000 1 Array#method_missing
0.02 0.000 0.000 0.000 0.000 1 String#%
0.01 0.000 0.000 0.000 0.000 1 BasicObject#instance_eval
0.01 0.000 0.000 0.000 0.000 1 Symbol#=~
0.00 0.000 0.000 0.000 0.000 2 Symbol#to_s
0.00 0.000 0.000 0.000 0.000 1 Module#method_added

  • indicates recursively called methods
    Thread ID: 2151954760
    Total: 0.440300
    Sort by: self_time

    %self total self wait child calls name
    39.00 0.315 0.172 0.000 0.143 5000 BasicObject#instance_eval
    24.41 0.143 0.107 0.000 0.036 5000 Array#sort
    13.89 0.424 0.061 0.000 0.363 5000 Array#method_missing
    8.17 0.036 0.036 0.000 0.000 30000 Fixnum#<=>
    6.08 0.027 0.027 0.000 0.000 5000 Symbol#=~
    4.77 0.021 0.021 0.000 0.000 5000 String#%
    3.66 0.440 0.016 0.000 0.424 1 Integer#times
    0.01 0.440 0.000 0.000 0.440 1 Global#[No method]

  • indicates recursively called methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment