Skip to content

Instantly share code, notes, and snippets.

@NilsHaldenwang
Created September 14, 2011 09:06
Show Gist options
  • Save NilsHaldenwang/1216151 to your computer and use it in GitHub Desktop.
Save NilsHaldenwang/1216151 to your computer and use it in GitHub Desktop.
require "benchmark"
def p_q_str_to_num(str)
str =~ /^p(\d+)q(\d+)$/
($1+$2).to_i
end
arr = (1..100000).map {"p#{rand(1000)}q#{rand(1000)}"}
Benchmark.bmbm do |x|
x.report("sort") { arr.sort { |x,y| p_q_str_to_num(x) <=> p_q_str_to_num(y) } }
x.report("sort_by") { arr.sort_by { |id| id =~ /^p(\d+)q(\d+)$/; ($1+$2).to_i } }
end
Rehearsal -------------------------------------------
sort 7.243000 0.000000 7.243000 ( 7.036000)
sort_by 0.997000 0.000000 0.997000 ( 0.997000)
---------------------------------- total: 8.240000sec
user system total real
sort 5.726000 0.000000 5.726000 ( 5.726000)
sort_by 0.695000 0.000000 0.695000 ( 0.695000)
Rehearsal -------------------------------------------
sort 12.080000 0.010000 12.090000 ( 12.535100)
sort_by 1.120000 0.010000 1.130000 ( 1.286980)
--------------------------------- total: 13.220000sec
user system total real
sort 10.890000 0.010000 10.900000 ( 10.938454)
sort_by 0.750000 0.010000 0.760000 ( 0.823790)
Rehearsal -------------------------------------------
sort 12.040000 0.030000 12.070000 ( 12.116498)
sort_by 0.440000 0.000000 0.440000 ( 0.438764)
--------------------------------- total: 12.510000sec
user system total real
sort 10.020000 0.030000 10.050000 ( 10.054058)
sort_by 0.410000 0.000000 0.410000 ( 0.416572)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment