Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Last active December 1, 2016 05:51
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 odedlaz/84840b070f3704d1a335f4203d716747 to your computer and use it in GitHub Desktop.
Save odedlaz/84840b070f3704d1a335f4203d716747 to your computer and use it in GitHub Desktop.
from __future__ import print_function
import os
import sys
# look at timeit.py gist
# https://gist.github.com/odedlaz/7811f703cc30a9d266817eaa4014ba7a
from random import randint
from timeit import TimeIt
from six.moves import range, cStringIO
class cStringIOStringBuilder(object):
def __init__(self, seed=None):
self._sf = cStringIO()
if seed:
self._sf.write(seed)
def __iadd__(self, other):
self._sf.write(other)
return self
def __repr__(self):
return str(self)
def __str__(self):
tell = self._sf.tell()
self._sf.seek(0)
txt = self._sf.read()
self._sf.seek(tell)
return txt
class JoinStringBuilder(object):
def __init__(self, seed=None):
self.l = [] if not seed else [seed]
def __iadd__(self, other):
self.l.append(other)
return self
def __repr__(self):
return str(self)
def __str__(self):
return "".join(self.l)
iterations = int(os.getenv("ITERATIONS", 1))
runs = {"+=": "text",
"cstringio": cStringIOStringBuilder("text"),
"str.join": JoinStringBuilder("text")}
for scope_name, s in runs.items():
with TimeIt(scope_name=scope_name,
fd=sys.stderr):
for _ in range(iterations):
s += str(randint(0, 1000))
print(str(s))
s = bytearray()
with TimeIt(scope_name="bytearray",
fd=sys.stderr):
for _ in range(iterations):
if six.PY3:
s += str(randint(0, 1000)).encode()
else:
s += str(randint(0, 1000))
print(str(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment