Created
May 7, 2011 22:19
-
-
Save aprescott/960903 to your computer and use it in GitHub Desktop.
Find the lowest multiple of some number greater than or equal to some other number.
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
def foo(n, m) | |
return n if n % m == 0 | |
n + m - (n % m) | |
end | |
foo(25, 7) #=> 28 | |
foo(28, 7) #=> 28 | |
foo(29, 7) #=> 35 | |
# No branching. | |
def bar(n, m) | |
n + (m - n % m) % m | |
end | |
bar(25, 7) #=> 28 | |
bar(28, 7) #=> 28 | |
bar(29, 7) #=> 35 |
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" | |
# ruby 1.9.2p180 (2011-02-18 revision 30909) [i686-linux] | |
Benchmark.realtime { 1_000_000.times { foo(25, 7) } } #=> 0.4824531078338623 | |
Benchmark.realtime { 1_000_000.times { bar(25, 7) } } #=> 0.42949914932250977 | |
Benchmark.realtime { 1_000_000.times { foo(28, 7) } } #=> 0.3901078701019287 | |
Benchmark.realtime { 1_000_000.times { bar(28, 7) } } #=> 0.43618083000183105 | |
Benchmark.realtime { 1_000_000.times { foo(29, 7) } } #=> 0.4811720848083496 | |
Benchmark.realtime { 1_000_000.times { bar(29, 7) } } #=> 0.43199920654296875 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment