Created
October 25, 2019 17:59
-
-
Save christopherzimmerman/c9cfba7cf4d3782494f0453444e82213 to your computer and use it in GitHub Desktop.
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 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 | |
a = 0 | |
Benchmark.ips do |b| | |
b.report("step from class") do | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
f.step_from_class { |i| a &+= i } | |
end | |
b.report("step_from_explicit_literal") do | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
f.step_from_explicit(100_000, 1) { |i| a &+= i } | |
end | |
b.report("step_from_explicit variable") do | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
f.step_from_explicit(n, step) { |i| a &+= i } | |
end | |
b.report("times explicit single step") do | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
f.times_explicit_single_step { |i| a &+= i } | |
end | |
b.report("times step from stride") do | |
n = 100_000 | |
step = 1 | |
f = Foo.new(n, step) | |
f.times_step_from_stride { |i| a &+= i } | |
end | |
end | |
puts a | |
# step from class 9.78k (102.29µs) (± 6.42%) 16.0B/op 7579.76× slower | |
# step_from_explicit_literal 74.10M ( 13.50ns) (±10.92%) 16.0B/op fastest | |
# step_from_explicit variable 71.71M ( 13.94ns) (±11.56%) 16.0B/op 1.03× slower | |
# times explicit single step 24.85k ( 40.24µs) (± 8.88%) 16.0B/op 2981.49× slower | |
# times step from stride 15.72k ( 63.62µs) (± 2.88%) 16.0B/op 4714.64× slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment