Created
February 3, 2016 18:33
-
-
Save TallGirlVanessa/e671adb91e8918c74b40 to your computer and use it in GitHub Desktop.
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 | |
from StringIO import StringIO | |
from cStringIO import StringIO as cStringIO | |
from tempfile import TemporaryFile | |
closure = dict() | |
def generate_test_data(size=1000): | |
closure.clear() | |
closure['test_data'] = bytearray((val % 256 for val in xrange(0, size))) | |
closure['one_stringio'] = StringIO() | |
closure['one_cstringio'] = cStringIO() | |
closure['one_tempfile'] = TemporaryFile() | |
def write_and_read_test_data(flo): | |
flo.write(closure['test_data']) | |
flo.seek(0) | |
closure['output'] = flo.read() | |
def use_stringio(): | |
flo = StringIO() | |
write_and_read_test_data(flo) | |
flo.close() | |
def use_cstringio(): | |
flo = cStringIO() | |
write_and_read_test_data(flo) | |
flo.close() | |
def use_tempfile(): | |
flo = TemporaryFile() | |
write_and_read_test_data(flo) | |
flo.close() | |
def use_one_stringio(): | |
flo = closure['one_stringio'] | |
flo.seek(0) | |
flo.truncate() | |
write_and_read_test_data(flo) | |
def use_one_cstringio(): | |
flo = closure['one_cstringio'] | |
flo.seek(0) | |
flo.truncate() | |
write_and_read_test_data(flo) | |
def use_one_tempfile(): | |
flo = closure['one_tempfile'] | |
flo.seek(0) | |
flo.truncate() | |
write_and_read_test_data(flo) | |
def sizeof_fmt(num, suffix='B'): | |
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: | |
if abs(num) < 1024.0: | |
return "%3.1f%s%s" % (num, unit, suffix) | |
num /= 1024.0 | |
return "%.1f%s%s" % (num, 'Yi', suffix) | |
def profile(test_name, test_function, passes): | |
results = timeit.repeat(test_function, repeat=3, number=passes) | |
print '{:15} {:.4f} {:.4f} {:.4f}'.format(test_name + ':', *results) | |
def trial(passes, size): | |
print 'Using {} passes with size {}'.format(passes, sizeof_fmt(size)) | |
generate_test_data(size) | |
profile('New StringIO', use_stringio, passes) | |
profile('Same StringIO', use_one_stringio, passes) | |
closure['one_stringio'].close() | |
profile('New cStringIO', use_cstringio, passes) | |
profile('Same cStringIO', use_one_cstringio, passes) | |
closure['one_cstringio'].close() | |
profile('New tempfile', use_tempfile, passes) | |
profile('Same tempfile', use_one_tempfile, passes) | |
closure['one_tempfile'].close() | |
print '==============================================================' | |
if __name__ == '__main__': | |
trial(1000, 1024) | |
trial(1000, 1024 * 100) | |
trial(1000, 1024 * 1024) | |
trial(1000, 1024 * 1024 * 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment