Skip to content

Instantly share code, notes, and snippets.

@gwillem
Created January 20, 2017 14:36
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 gwillem/bf51d4ff4650e0eac1e525034aebedbb to your computer and use it in GitHub Desktop.
Save gwillem/bf51d4ff4650e0eac1e525034aebedbb to your computer and use it in GitHub Desktop.
python string replace benchmark
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