Skip to content

Instantly share code, notes, and snippets.

@bungoume
Last active August 29, 2015 14:17
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 bungoume/0a05c14c972c2e2ac95c to your computer and use it in GitHub Desktop.
Save bungoume/0a05c14c972c2e2ac95c to your computer and use it in GitHub Desktop.
python replace benchmark
import timeit
import re
def a(w):
w = w.replace('g', 'k')
w = w.replace('z', 's')
w = w.replace('d', 't')
w = re.sub(r'[bp]', 'h', w)
return w
def b(w):
w = w.replace('g', 'k')
w = w.replace('z', 's')
w = w.replace('d', 't')
w = w.replace('b', 'h')
w = w.replace('p', 'h')
return w
def c(w):
return w.translate(str.maketrans('gzdbp', 'ksthh'))
word = "gagiguzazizudadobabibupapipu"
print(timeit.timeit('a(word)', number=100000, setup="from __main__ import a, word"))
print(timeit.timeit('b(word)', number=100000, setup="from __main__ import b, word"))
print(timeit.timeit('c(word)', number=100000, setup="from __main__ import c, word"))
@bungoume
Copy link
Author

python bench.py
0.36540638228603406
0.149840317632226
0.2814383770573038

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment