Skip to content

Instantly share code, notes, and snippets.

@WaKeMaTTa
Created March 21, 2021 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WaKeMaTTa/fec95895116638eb3c83d1ba603d0225 to your computer and use it in GitHub Desktop.
Save WaKeMaTTa/fec95895116638eb3c83d1ba603d0225 to your computer and use it in GitHub Desktop.
require "benchmark"
include Benchmark
n = 100_000_000
def while_loop(n = 100_000_000)
i = 0
s = 0
while i <= n
s += i
i += 1
end
s
end
def for_loop(n = 100_000_000)
s = 0
for i in 1..n
s += i
end
s
end
def loop_loop(n = 100_000_000)
i = 0
s = 0
loop do
s += i
i += 1
break if i > n
end
s
end
def times_loop(n = 100_000_000)
s = 0
(n + 1).times do |i|
s += i
end
s
end
def upto_loop(n = 100_000_000)
s = 0
1.upto(n) do |i|
s += i
end
s
end
Benchmark.benchmark(CAPTION, 7, FORMAT) do |x|
x.report("while:") { while_loop }
x.report("for:") { for_loop }
x.report("loop:") { loop_loop }
x.report("times:") { times_loop }
x.report("upto:") { upto_loop }
end
# Using Ruby 3.0.0
# user system total real
# while: 3.249034 0.000211 3.249245 ( 3.250387)
# for: 6.781550 0.000000 6.781550 ( 6.783788)
# loop: 8.140319 0.000000 8.140319 ( 8.143120)
# times: 6.109319 0.003978 6.113297 ( 6.144387)
# upto: 6.548618 0.000008 6.548626 ( 6.579711)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment