Created
December 5, 2019 04:04
-
-
Save firejox/806a24c8c0a4dc3463b112cc234a6607 to your computer and use it in GitHub Desktop.
Array rotation
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" | |
class Array | |
def new_rotate!(n = 1) | |
return self if empty? | |
sz = self.size | |
n %= sz | |
return self if n == 0 | |
tmp = Slice.new(to_unsafe, sz) | |
tmp[0...n].reverse! | |
tmp[n..-1].reverse! | |
tmp.reverse! | |
self | |
end | |
end | |
x3 = (0...3).to_a | |
x10 = (0...10).to_a | |
x100 = (0...100).to_a | |
x1000 = (0...1000).to_a | |
Benchmark.ips do |x| | |
x.report("3 rotate! 2") { x3.rotate!(2) } | |
x.report("3 new_rotate! 2") { x3.new_rotate!(2) } | |
end | |
Benchmark.ips do |x| | |
x.report("10 rotate! 3") { x10.rotate!(3) } | |
x.report("10 new_rotate! 3") { x10.new_rotate!(3) } | |
end | |
Benchmark.ips do |x| | |
x.report("100 rotate! 30") { x100.rotate!(30) } | |
x.report("100 new_rotate! 30") { x100.new_rotate!(30) } | |
end | |
Benchmark.ips do |x| | |
x.report("1000 rotate! 300") { x1000.rotate!(300) } | |
x.report("1000 new_rotate! 300") { x1000.new_rotate!(300) } | |
end |
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
3 rotate! 2 8.92M (112.06ns) (± 6.49%) 49.0B/op 3.40× slower | |
3 new_rotate! 2 30.34M ( 32.96ns) (± 2.97%) 0.0B/op fastest | |
10 rotate! 3 9.67M (103.43ns) (± 4.34%) 65.0B/op 2.58× slower | |
10 new_rotate! 3 24.96M ( 40.07ns) (± 2.89%) 0.0B/op fastest | |
100 rotate! 30 5.12M (195.25ns) (± 5.70%) 161B/op 1.49× slower | |
100 new_rotate! 30 7.61M (131.47ns) (± 2.62%) 0.0B/op fastest | |
1000 rotate! 300 352.55k ( 2.84µs) (± 2.22%) 2.03kB/op 3.05× slower | |
1000 new_rotate! 300 1.07M (931.43ns) (± 2.97%) 0.0B/op fastest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment