Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # pixels_timeit.py
- import sys
- import timeit
- N = 1 # number of executions of each algorithm
- R = 3 # number of repeations of executions
- # common setup for all algorithms - is not included in algorithm timing
- setup = """
- from random import randint, sample, seed
- from PIL import Image
- from array import array
- seed(0)
- background = 0 # default color of pixels not defined in dictionary
- width, height = 300, 300
- # create test dict of input data defining half of the pixel coords in image
- coords = sample([(x,y) for x in xrange(width) for y in xrange(height)],
- width * height // 2)
- d = {coord: randint(0, 255) for coord in coords}
- """
- algorithms = {
- "putpixel ": """
- im = Image.new('L', (width, height), color=background) # set bgrd
- for i in d:
- im.putpixel(i, d[i])
- """,
- "bytearray": """
- data = bytearray([background] * width * height)
- for (x, y), v in d.iteritems():
- data[x + y*width] = v
- im = Image.frombytes('L', (width, height), str(data))
- """,
- "put_array": """
- data = array("B", [0]) * (width * height)
- for i in d:
- x, y = i
- data[x + y * width] = d[i]
- im = Image.new('L', (width, height))
- im.putdata(tuple(data))
- """,
- "putdata ": """
- data = [background] * width * height
- for i in d:
- x, y = i
- data[x + y * width] = d[i]
- im = Image.new('L', (width, height))
- im.putdata(data)
- """
- }
- # execute and time algorithms, collecting results
- timings = [
- (label,
- min(timeit.repeat(algorithms[label], setup=setup, repeat=R, number=N)),
- ) for label in algorithms
- ]
- print 'fastest to slowest execution speeds (Python {}.{}.{})'.format(*sys.version_info[:3])
- print '*** best of {:d} repetitions\n'.format(R)
- longest = max(len(timing[0]) for timing in timings) # length of longest label
- ranked = sorted(timings, key=lambda t: t[1]) # ascending sort by execution time
- fastest = ranked[0][1]
- for timing in ranked:
- a,b,c = timing[0], timing[1], round(timing[1]/fastest, 2)
- sss = "{} : {:9.6f} ... {:9.2f}x slower".format(a,b,c)
- if ' 1.00x' in sss:
- sss = sss[:sss.index('...')]
- print sss
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement