Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Created June 29, 2018 21:09
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 JoelQ/90e89340a7d0207d0ab2f6e4e328a51b to your computer and use it in GitHub Desktop.
Save JoelQ/90e89340a7d0207d0ab2f6e4e328a51b to your computer and use it in GitHub Desktop.
Hamming Benchmark - Classic
class Hamming
def self.eager(s1, s2)
s1.chars.
zip(s2.chars).
count { |c1, c2| c1 != c2 }
end
def self.half_lazy(s1, s2)
s1.each_char.
zip(s2.each_char).
count { |c1, c2| c1 != c2 }
end
def self.full_lazy(s1, s2)
s1.each_char.lazy.
zip(s2.each_char.lazy).
count { |c1, c2| c1 != c2 }
end
end
require 'benchmark'
puts
puts "=== TIME - Short strings (25 chars) ==="
puts
short1 = "#{"A" * 23}TG"
short2 = "#{"A" * 23}CT"
Benchmark.bm do |x|
x.report("Eager ") { 100_000.times { Hamming.eager(short1, short2) } }
x.report("Half Lazy") { 100_000.times { Hamming.half_lazy(short1, short2) } }
x.report("Full Lazy") { 100_000.times { Hamming.full_lazy(short1, short2) } }
end
puts
puts "=== TIME - Medium strings (250 chars) ==="
puts
med1 = "#{"A" * 248}TG"
med2 = "#{"A" * 248}CT"
Benchmark.bm do |x|
x.report("Eager ") { 100_000.times { Hamming.eager(med1, med2) } }
x.report("Half Lazy") { 100_000.times { Hamming.half_lazy(med1, med2) } }
x.report("Full Lazy") { 100_000.times { Hamming.full_lazy(med1, med2) } }
end
puts
puts "=== TIME - Long strings (2500 chars) ==="
puts
long1 = "#{"A" * 2_448}TG"
long2 = "#{"A" * 2_448}CT"
Benchmark.bm do |x|
x.report("Eager ") { 100_000.times { Hamming.eager(long1, long2) } }
x.report("Half Lazy") { 100_000.times { Hamming.half_lazy(long1, long2) } }
x.report("Full Lazy") { 100_000.times { Hamming.full_lazy(long1, long2) } }
end
=== TIME - Short strings (25 chars) ===
user system total real
Eager 0.958450 0.001449 0.959899 ( 0.960787)
Half Lazy 4.644654 0.040755 4.685409 ( 4.692011)
Full Lazy 7.147588 0.056425 7.204013 ( 7.215803)
=== TIME - Medium strings (250 chars) ===
user system total real
Eager 8.241543 0.016843 8.258386 ( 8.271243)
Half Lazy 40.566289 0.147004 40.713293 ( 40.781184)
Full Lazy 57.133163 0.135730 57.268893 ( 57.319992)
=== TIME - Long strings (2500 chars) ===
user system total real
Eager 99.702533 0.138383 99.840916 ( 99.964436)
Half Lazy377.757468 0.471557 378.229025 (378.467603)
Full Lazy518.590383 0.622551 519.212934 (519.562480)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment