Advertisement
here2share

# pixels_timeit.py

Nov 28th, 2019
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. # pixels_timeit.py
  2.  
  3. import sys
  4. import timeit
  5.  
  6. N = 1  # number of executions of each algorithm
  7. R = 3  # number of repeations of executions
  8.  
  9. # common setup for all algorithms - is not included in algorithm timing
  10. setup = """
  11. from random import randint, sample, seed
  12. from PIL import Image
  13. from array import array
  14.  
  15. seed(0)
  16. background = 0  # default color of pixels not defined in dictionary
  17. width, height = 300, 300
  18.  
  19. # create test dict of input data defining half of the pixel coords in image
  20. coords = sample([(x,y) for x in xrange(width) for y in xrange(height)],
  21.                 width * height // 2)
  22. d = {coord: randint(0, 255) for coord in coords}
  23. """
  24.  
  25. algorithms = {
  26.     "putpixel ": """
  27.         im = Image.new('L', (width, height), color=background)  # set bgrd
  28.         for i in d:
  29.             im.putpixel(i, d[i])
  30.     """,
  31.  
  32.     "bytearray": """
  33.         data = bytearray([background] * width * height)
  34.         for (x, y), v in d.iteritems():
  35.             data[x + y*width] = v
  36.         im = Image.frombytes('L', (width, height), str(data))
  37.     """,
  38.  
  39.     "put_array": """
  40.         data = array("B", [0]) * (width * height)
  41.         for i in d:
  42.             x, y = i
  43.             data[x + y * width] = d[i]
  44.         im = Image.new('L', (width, height))
  45.         im.putdata(tuple(data))
  46.     """,
  47.  
  48.     "putdata  ": """
  49.         data = [background] * width * height
  50.         for i in d:
  51.             x, y = i
  52.             data[x + y * width] = d[i]
  53.         im = Image.new('L', (width, height))
  54.         im.putdata(data)
  55.     """
  56. }
  57.  
  58. # execute and time algorithms, collecting results
  59. timings = [
  60.     (label,
  61.      min(timeit.repeat(algorithms[label], setup=setup, repeat=R, number=N)),
  62.     ) for label in algorithms
  63. ]
  64.  
  65. print 'fastest to slowest execution speeds (Python {}.{}.{})'.format(*sys.version_info[:3])
  66. print '*** best of {:d} repetitions\n'.format(R)
  67. longest = max(len(timing[0]) for timing in timings)  # length of longest label
  68. ranked = sorted(timings, key=lambda t: t[1])  # ascending sort by execution time
  69. fastest = ranked[0][1]
  70. for timing in ranked:
  71.     a,b,c = timing[0], timing[1], round(timing[1]/fastest, 2)
  72.     sss = "{} : {:9.6f} ... {:9.2f}x slower".format(a,b,c)
  73.     if ' 1.00x' in sss:
  74.         sss = sss[:sss.index('...')]
  75.     print sss
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement