Created
October 25, 2019 14:39
-
-
Save asterite/22b1bcadd58575c8962e16404a2a230d to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
struct Foo | |
def initialize(@size : Int32, @stride : Int32) | |
end | |
def step_from_class | |
0.step(to: @size, by: @stride) do |i| | |
yield i | |
end | |
end | |
def step_from_explicit(n : Int32, step : Int32) | |
0.step(to: n, by: step) do |i| | |
yield i | |
end | |
end | |
def times_explicit_single_step | |
i = @size ^ @size | |
while i < @size | |
yield i | |
i += 1 | |
end | |
end | |
def times_step_from_stride | |
i = @size ^ @size | |
while i < @size | |
yield i | |
i += @stride | |
end | |
end | |
end | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
Benchmark.ips do |b| | |
b.report("step from class") { f.step_from_class { |i| 2*i } } | |
b.report("step_from_explicit_literal") { f.step_from_explicit(100_000, 1) { |i| 2*i } } | |
b.report("step_from_explicit variable") { f.step_from_explicit(n, step) { |i| 2*i } } | |
b.report("times explicit single step") { f.times_explicit_single_step { |i| 2*i } } | |
b.report("times step from stride") { f.times_step_from_stride { |i| 2*i } } | |
end | |
# step from class 20.62k ( 48.50µs) (± 6.12%) 0.0B/op 1.15× slower | |
# step_from_explicit_literal 23.68k ( 42.24µs) (± 5.95%) 0.0B/op fastest | |
# step_from_explicit variable 21.63k ( 46.24µs) (± 4.48%) 0.0B/op 1.09× slower | |
# times explicit single step 21.54k ( 46.43µs) (± 4.84%) 0.0B/op 1.10× slower | |
# times step from stride 22.30k ( 44.84µs) (± 1.26%) 0.0B/op 1.06× slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment