Created
January 20, 2017 14:36
-
-
Save gwillem/bf51d4ff4650e0eac1e525034aebedbb to your computer and use it in GitHub Desktop.
python string 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 time | |
import re | |
import string | |
src = '_ ' * 2**20 # 2MB | |
whitespacere = re.compile('\s') | |
def replace(): | |
return src.replace(' ', '').replace('\r', '').replace('\n', '').replace('\t', '') | |
def sub(): | |
return whitespacere.sub('', src) | |
def translate(): | |
return src.translate(None, string.whitespace) | |
def testrun(f, i=500): | |
start = time.time() | |
for _ in range(i): | |
f() | |
end = time.time() | |
print("{} for {} runs of {}".format( | |
end - start, | |
i, | |
f.__name__ | |
)) | |
if __name__ == '__main__': | |
testrun(translate) | |
testrun(replace) | |
testrun(sub) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment