Skip to content

Instantly share code, notes, and snippets.

@asterite
Created October 25, 2019 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asterite/caf1d821ab23a4f6195ec39135b67f4e to your computer and use it in GitHub Desktop.
Save asterite/caf1d821ab23a4f6195ec39135b67f4e to your computer and use it in GitHub Desktop.
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
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 835.01M ( 1.20ns) (± 7.91%) 0.0B/op 1.01× slower
# step_from_explicit_literal 834.18M ( 1.20ns) (± 8.61%) 0.0B/op 1.01× slower
# step_from_explicit variable 830.88M ( 1.20ns) (± 8.82%) 0.0B/op 1.02× slower
# times explicit single step 845.11M ( 1.18ns) (± 7.10%) 0.0B/op fastest
# times step from stride 836.71M ( 1.20ns) (±10.16%) 0.0B/op 1.01× slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment