manveru (owner)

Fork Of

gist: 58562 by Pistos "while true" is faster than...

Revisions

gist: 58565 Download_button fork
public
Public Clone URL: git://gist.github.com/58565.git
Embed All Files: show embed
loop_vs_while.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def by_loop
  loop do
    break if yield
  end
end
 
def by_while
  while true
    break if yield
  end
end
 
require 'benchmark'
x = 10_000_000
 
Benchmark.bmbm(20) do |b|
  b.report('loop: '){ n = 0; by_loop{ (n += 1) == x }}
  b.report('while: '){ n = 0; by_while{ (n += 1) == x }}
end
 
results.txt #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ruby 1.8.7 (2008-08-11 patchlevel 72) [x86_64-linux]
Rehearsal -------------------------------------------------------
loop: 20.310000 0.120000 20.430000 ( 20.441405)
while: 14.490000 0.030000 14.520000 ( 14.524623)
--------------------------------------------- total: 34.950000sec
 
                          user system total real
loop: 20.490000 0.110000 20.600000 ( 20.607152)
while: 15.020000 0.040000 15.060000 ( 15.054473)
 
ruby 1.9.2dev (2009-02-05 trunk 22073) [x86_64-linux]
Rehearsal -------------------------------------------------------
loop: 4.680000 0.000000 4.680000 ( 4.681246)
while: 2.830000 0.000000 2.830000 ( 2.826771)
---------------------------------------------- total: 7.510000sec
 
                          user system total real
loop: 4.660000 0.000000 4.660000 ( 4.660789)
while: 2.810000 0.010000 2.820000 ( 2.816847)