Skip to content

Instantly share code, notes, and snippets.

@methane
Last active July 29, 2023 02:05
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 methane/5c6153c564d9508199a81c48d33161eb to your computer and use it in GitHub Desktop.
Save methane/5c6153c564d9508199a81c48d33161eb to your computer and use it in GitHub Desktop.
bench_indent.py
# https://github.com/python/cpython/pull/107374
import sys
import textwrap
import timeit
filename = "Objects/unicodeobject.c"
if len(sys.argv) > 1:
filename = sys.argv[1]
with open(filename) as f:
text = f.read()
print(f"{filename=!r} {len(text.splitlines())} lines.")
predicates = {
"lstrip": str.lstrip,
"not x.isspace()": lambda x: not x.isspace(),
"x and not x.isspace()": lambda x: x and not x.isspace(),
}
for name, predicate in predicates.items():
it = timeit.Timer(lambda: textwrap.indent(text, " "*4, predicate))
result = it.repeat(number=1000)
result.sort()
print(f"{name:>25}: {result[0]:.3f}msec")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment