Skip to content

Instantly share code, notes, and snippets.

@l15n
Created June 28, 2012 02:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save l15n/3008383 to your computer and use it in GitHub Desktop.
Save l15n/3008383 to your computer and use it in GitHub Desktop.
Roughly estimate usage of Enumerable methods
#! /usr/bin/env ruby
#
# enumetric.rb
#
# Rough estimate of usage/non-usage of Enumerable methods
TRIVIAL_METHODS = [:first, :count, :to_a]
def count_usage(method, dir = '.')
method_delimiter = '[\s\.\{\(=]'
method = method.to_s.sub('?','\?')
cmd = "ack --no-group --ruby \"\\.#{method}#{method_delimiter}\" #{dir}"
IO.popen(cmd).count
end
def measure_enumerable_usage(dir = '.')
Enumerable.instance_methods.each_with_object({}) { |m, set|
set[m] = count_usage(m, dir)
}
end
def tally_enumetric(dir = '.')
each_count = count_usage('each', dir)
enumerable_usage = measure_enumerable_usage(dir)
enumerable_count = enumerable_usage.values.reduce(&:+)
most_common = enumerable_usage.max_by {|k,v| v}
least_common = enumerable_usage.reject{|k,v| v.zero?}.min_by {|k,v| v}
non_trivial = enumerable_usage.reject {|k,v| TRIVIAL_METHODS.member? k }
ratio = 100.0 * each_count / (each_count + enumerable_count)
non_trivial_ratio = 100.0 * each_count / (each_count + non_trivial.values.reduce(&:+))
puts "#each count: #{each_count}"
puts "Enumerable method usage: #{enumerable_count}"
puts "Each ratio (lower is better): #{ratio.round(2)}%"
puts "Non-trivial each ratio: #{non_trivial_ratio.round(2)}%"
puts "Most Used: #{most_common[0]} / #{most_common[1]} times"
puts "Least Used: #{least_common[0]} / #{least_common[1]} times"
puts "Used once: #{enumerable_usage.select{|k,v| v == 1}.map{|k,v| k}}"
puts "Never used: #{enumerable_usage.select{|k,v| v.zero?}.map{|k,v| k}}"
puts "All usage: #{enumerable_usage.reject{|k,v| v.zero?}.sort_by {|k,v| v}.map{|k,v| "#{k}: #{v}"}}"
end
if __FILE__ == $0
if dir = ARGV[0]
tally_enumetric(dir)
else
tally_enumetric
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment