Last active
August 29, 2015 14:17
-
-
Save bungoume/0a05c14c972c2e2ac95c to your computer and use it in GitHub Desktop.
python replace 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
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")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
python bench.py
0.36540638228603406
0.149840317632226
0.2814383770573038