Created
March 26, 2013 06:55
-
-
Save prcaen/5243598 to your computer and use it in GitHub Desktop.
Benchmark ruby loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "benchmark" | |
n = 5000000 | |
Benchmark.bmbm do |x| | |
x.report("while:") { i = 1; while i < n do; a = "1 and #{i}"; i += 1; end } | |
x.report("for loop:") { for i in 1..n; a = "1 and #{i}"; end } | |
x.report("times:") { n.times do |i| ; a = "1 and #{i}"; end } | |
x.report("upto:") { 1.upto(n) do |i| ; a = "1 and #{i}"; end } | |
x.report("until:") { i = 1; until i > n do; a = "1 and #{i}"; i += 1; end } | |
x.report("each:") { (1..n).each do |i|; ; a = "1 and #{i}"; end } | |
end | |
## RESULTS | |
# Rehearsal ---------------------------------------------- | |
# while: 2.020000 0.000000 2.020000 ( 2.024218) | |
# for loop: 2.280000 0.000000 2.280000 ( 2.279738) | |
# times: 2.230000 0.000000 2.230000 ( 2.227971) | |
# upto: 2.200000 0.000000 2.200000 ( 2.206145) | |
# until: 2.010000 0.000000 2.010000 ( 2.006059) | |
# each: 2.230000 0.000000 2.230000 ( 2.233922) | |
# ------------------------------------ total: 12.970000sec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment