Last active
August 29, 2015 14:10
-
-
Save dannvix/99b174d301bbc3426d67 to your computer and use it in GitHub Desktop.
Hamming distance implementation benchmark
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
#!/usr/bin/env python | |
# ref. https://medium.com/on-coding/shorter-code-is-inconsiderate-41cce917b51b | |
import timeit | |
setup = ''' | |
def hamming_fp(a, b): | |
return sum(x != y for x, y in map(None, a, b)) | |
def hamming(s1, s2): | |
hamming_number = 0 | |
minlength = min(len(s1), len(s2)) | |
maxlength = max(len(s1), len(s2)) | |
for i in range(minlength): | |
if (s1[i] != s2[i]): | |
hamming_number += 1 | |
hamming_number += maxlength - minlength | |
return hamming_number | |
s1 = 'abcdegadbfuabf' | |
s2 = 'xbcd28nf902n3' | |
''' | |
number = 1000000 | |
print timeit.timeit('hamming_fp(s1, s2)', setup=setup, number=number) | |
print timeit.timeit('hamming(s1, s2)', setup=setup, number=number) | |
''' | |
$ python hamming.py | |
4.19833397865 | |
3.22787094116 | |
$ python ─ [ 2014/12/01 22:25:42 ] ─┘ | |
Python 2.7.5 (default, Mar 9 2014, 22:15:05) | |
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin | |
>>> | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment