Skip to content

Instantly share code, notes, and snippets.

@ericmathison
Created October 7, 2020 19:36
Show Gist options
  • Save ericmathison/3dc0185e8af124566ab17f907508a4bd to your computer and use it in GitHub Desktop.
Save ericmathison/3dc0185e8af124566ab17f907508a4bd to your computer and use it in GitHub Desktop.
Benchmarking codewars solutions
require 'benchmark/ips'
def triangle_calc(row)
return row if row.length == 1
triangle_calc(row.chars.each_cons(2).map do |a, b|
if a == b
a
else
(%w[R G B] - [a, b]).first
end
end.join)
end
LOOKUP = {
'R' => {
'R' => 'R',
'G' => 'B',
'B' => 'G'
},
'B' => {
'R' => 'G',
'B' => 'B',
'G' => 'R'
},
'G' => {
'R' => 'B',
'B' => 'R',
'G' => 'G'
}
}
def triangle_lookup(row)
# your code here
return row if row.length == 1
triangle_lookup(row.each_char.each_cons(2).map {|(a, b)| LOOKUP[a][b]}.join(''))
end
Benchmark.ips do |x|
x.report('triangle_calc') { triangle_calc('RBGRGRGBGGRRBBBGRGBGGGRGRGBGRBRBGBGRGRGRGBGGRRGGGRGBGGRGRGRGGBGRGRRGGGRRRGGGBBGBGRRBGBRGRGBBBGRRRBRBRRRBGBGRGRGBBGRG') }
x.report('triangle_lookup') { triangle_lookup('RBGRGRGBGGRRBBBGRGBGGGRGRGBGRBRBGBGRGRGRGBGGRRGGGRGBGGRGRGRGGBGRGRRGGGRRRGGGBBGBGRRBGBRGRGBBBGRRRBRBRRRBGBGRGRGBBGRG') }
end
# eric@penguin ~/Desktop $ ruby bench.rb
# Warming up --------------------------------------
# triangle_calc 26.000 i/100ms
# triangle_lookup 40.000 i/100ms
# Calculating -------------------------------------
# triangle_calc 317.879 (± 1.9%) i/s - 1.612k in 5.072790s
# triangle_lookup 400.224 (± 1.2%) i/s - 2.040k in 5.098042s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment