Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hamming benchmarks - Style comparisons
class Hamming
def self.zip_count(s1, s2)
s1.chars.
zip(s2.chars).
count { |c1, c2| c1 != c2 }
end
def self.for_loop(s1, s2)
distance = 0
for i in 0...s1.length
if s1[i] != s2[i]
distance = distance + 1
end
end
distance
end
def self.indexes(s1, s2)
distance = 0
s1.chars.each_with_index do |j, i|
distance = distance + 1 if s1[i] != s2[i]
end
distance
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("Zip + Count ") { 100_000.times { Hamming.zip_count(short1, short2) } }
x.report("For Loop ") { 100_000.times { Hamming.for_loop(short1, short2) } }
x.report("Each with index") { 100_000.times { Hamming.indexes(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("Zip + Count ") { 100_000.times { Hamming.zip_count(med1, med2) } }
x.report("For Loop ") { 100_000.times { Hamming.for_loop(med1, med2) } }
x.report("Each with index") { 100_000.times { Hamming.indexes(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("Zip + Count ") { 100_000.times { Hamming.zip_count(long1, long2) } }
x.report("For Loop ") { 100_000.times { Hamming.for_loop(long1, long2) } }
x.report("Each with index") { 100_000.times { Hamming.indexes(long1, long2) } }
end
=== TIME - Short strings (25 chars) ===
user system total real
Zip + Count 0.916516 0.000370 0.916886 ( 0.916935)
For Loop 0.741585 0.000282 0.741867 ( 0.741969)
Each with index 1.048152 0.000745 1.048897 ( 1.049324)
=== TIME - Medium strings (250 chars) ===
user system total real
Zip + Count 7.439889 0.004716 7.444605 ( 7.446956)
For Loop 6.939437 0.003735 6.943172 ( 6.945046)
Each with index 9.205381 0.004338 9.209719 ( 9.211600)
=== TIME - Long strings (2500 chars) ===
user system total real
Zip + Count 97.230279 0.130710 97.360989 ( 97.460118)
For Loop 68.952586 0.068595 69.021181 ( 69.065801)
Each with index 96.847159 0.118325 96.965484 ( 97.052869)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment