a pastebin project

Tests for Python performance: ht

This post has 1 comment thread shown at the end of this page.

  1. from timeit import Timer
  2. import datetime
  3.  
  4. # Method returning a generator
  5. class A(object):
  6.   def __iter__(self):
  7.     counter = 0
  8.     while True:
  9.       counter += 1
  10.       yield counter
  11.  
  12. # Custom iterator class
  13. class B(object):
  14.   def __init__(self):
  15.     self.counter = 0
  16.   def __iter__(self):
  17.     return self
  18.   def next(self):
  19.     self.counter += 1
  20.     return self.counter
  21.  
  22. # B with slots
  23. class Bs(object):
  24.   __slots__ = ['counter']
  25.   def __init__(self):
  26.     self.counter = 0
  27.   def __iter__(self):
  28.     return self
  29.   def next(self):
  30.     self.counter += 1
  31.     return self.counter
  32.  
  33. # Comment from the article
  34. class C(object):
  35.     def __iter__(self):
  36.         self.counter = 0
  37.         while True:
  38.             yield self.counter
  39.             self.counter += 1
  40.     def skipto(self, n):
  41.         self.counter = n
  42.  
  43. # C with slots
  44. class Cs(object):
  45.     __slots__ = ['counter']
  46.     def __iter__(self):
  47.         self.counter = 0
  48.         while True:
  49.             yield self.counter
  50.             self.counter += 1
  51.     def skipto(self, n):
  52.         self.counter = n
  53.  
  54. if __name__ == '__main__':
  55.     print "Test A:"
  56.     print Timer("cnt.next()", "from gaap import A; cnt = iter(A())").repeat(3, 100000)
  57.  
  58.     print "Test B:"
  59.     print Timer("cnt.next()", "from gaap import B; cnt = iter(B())").repeat(3, 100000)
  60.  
  61.     print "Test Bs:"
  62.     print Timer("cnt.next()", "from gaap import Bs; cnt = iter(Bs())").repeat(3, 100000)
  63.  
  64.     print "Test C:"
  65.     print Timer("cnt.next()", "from gaap import C; cnt = iter(C())").repeat(3, 100000)
  66.  
  67.     print "Test Cs:"
  68.     print Timer("cnt.next()", "from gaap import Cs; cnt = iter(Cs())").repeat(3, 100000)

advertising

Create a Paste

Please enter your new post below (or upload a file instead):





Please note that information posted here will not expire by default. If you want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords.

worth-right