Skip to content

Instantly share code, notes, and snippets.

@cwcowellshah
Last active May 6, 2019 01:45
Show Gist options
  • Save cwcowellshah/29f1b83af389ad78fe0b to your computer and use it in GitHub Desktop.
Save cwcowellshah/29f1b83af389ad78fe0b to your computer and use it in GitHub Desktop.
Good Ruby vs. Bad Ruby
# Here are two Ruby programs that do exactly the same thing. One is written to be readable and maintainable, and the other is not.
#
# BAD RUBY
#
d = Hash.new([])
File.foreach('scale_test_timing_log.csv') { |line| d[line.split(',')[2]] = d[line.split(',')[2]] << line.chomp.split(',')[3].to_f }
d.keys.sort.each { |act| File.open('a.csv', 'a') { |a| a.puts("#{act},#{((d[act].sort[((d[act].length - 1) / 2.0).floor] + d[act].sort[((d[act].length - 1) / 2.0).ceil]) / 2.0).round(1)},#{d[act].last},#{d[act].select { |elapsed_secs| elapsed_secs >= 4 }.length}") } }
#
# GOOD RUBY
#
ANALYSIS_CSV = 'scale_test_timing_analysis.csv'
DATA_CSV = 'scale_test_timing_log.csv'
MAX_ACCEPTABLE_ELAPSED_SECS = 4.0
data = Hash.new(Array.new)
# read in raw data
File.foreach(DATA_CSV) do |line|
line_parts = line.chomp.split(',')
action = line_parts[2]
elapsed_secs = line_parts[3].to_f
data[action] = data[action] << elapsed_secs
end
# prep the file that contains our analyzed results
File.write(ANALYSIS_CSV, "action,median elapsed secs,max elapsed secs,instances > #{MAX_ACCEPTABLE_ELAPSED_SECS} secs\n")
# analyze data and dump it to a file
actions = data.keys.sort
actions.each do |action|
elapsed_time_in_secs = data[action].sort
# find max elapsed time
max_elapsed_secs = elapsed_time_in_secs.last
# find median elapsed time
median_idx = (elapsed_time_in_secs.length - 1) / 2.0
median_elapsed_secs = ((elapsed_time_in_secs[median_idx.floor] + elapsed_time_in_secs[median_idx.ceil]) / 2.0).round(1)
# find number of instances that ran too slowly
slow_instances = elapsed_time_in_secs.select { |elapsed_secs| elapsed_secs >= MAX_ACCEPTABLE_ELAPSED_SECS }
# write analyzed data to a CSV file
File.open(ANALYSIS_CSV, 'a') do |analysis_csv|
analysis_csv.puts("#{action},#{median_elapsed_secs},#{max_elapsed_secs},#{slow_instances.length}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment