Skip to content

Instantly share code, notes, and snippets.

@jcdavison
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save jcdavison/a60b60f20d21b3fd506f to your computer and use it in GitHub Desktop.

Select an option

Save jcdavison/a60b60f20d21b3fd506f to your computer and use it in GitHub Desktop.
benchmark horizontal stars
require 'benchmark'

def coke(height)
  stars = 1
  height.times do |level|
    puts(" " * (height - (level + 1)) + "*" * stars)
    stars += 2
  end
end

def pepsi(height)
  stars = 1

  height.times do
    height.times do
      print " "
    end
    (1..stars).each do
      print "*"
    end
      height = height - 1
      stars = stars + 2
    print "\n"
  end

  print "\n"
end

omitting star output for brevity of write up.

puts "Pepsi"
puts Benchmark.measure { pepsi(5) }
  0.000000   0.000000   0.000000 (  0.000308)
puts "Coke"
puts Benchmark.measure { coke(5) }
  0.000000   0.000000   0.000000 (  0.000085)

Where height = 5

puts "Pepsi"
puts Benchmark.measure { pepsi(100) }
user       system     total     elapsed real time
0.000000   0.000000   0.000000 (  0.000308)


puts "Coke"
puts Benchmark.measure { coke(100) }
user       system     total     elapsed real time
0.000000   0.000000   0.000000 (  0.000085)

0.000308 / 0.000085 == 3.6x slower

Where height = 100

Pepsi(100)
user       system     total     elapsed real time
0.060000   0.040000   0.100000 (  0.115478)

Coke(100)
user       system     total     elapsed real time
0.010000   0.000000   0.010000 (  0.003107)

0.115478 / 0.003107 == 37.1x slower

@PeteVarley
Copy link

This is great feedback, I struggled with this problem. I was way far down a rabbit hole of needing nested loops before I stepped back and got a passing answer. I will keep this pattern in mind for the future.

Thanks!

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