- Tests for Python performance: ht
- Tuesday, July 21st, 2009 at 8:11:17am MDT
This post has 1 comment thread shown at the end of this page.
- from timeit import Timer
- import datetime
- # Method returning a generator
- class A(object):
- def __iter__(self):
- counter = 0
- while True:
- counter += 1
- yield counter
- # Custom iterator class
- class B(object):
- def __init__(self):
- self.counter = 0
- def __iter__(self):
- return self
- def next(self):
- self.counter += 1
- return self.counter
- # B with slots
- class Bs(object):
- __slots__ = ['counter']
- def __init__(self):
- self.counter = 0
- def __iter__(self):
- return self
- def next(self):
- self.counter += 1
- return self.counter
- # Comment from the article
- class C(object):
- def __iter__(self):
- self.counter = 0
- while True:
- yield self.counter
- self.counter += 1
- def skipto(self, n):
- self.counter = n
- # C with slots
- class Cs(object):
- __slots__ = ['counter']
- def __iter__(self):
- self.counter = 0
- while True:
- yield self.counter
- self.counter += 1
- def skipto(self, n):
- self.counter = n
- if __name__ == '__main__':
- print "Test A:"
- print Timer("cnt.next()", "from gaap import A; cnt = iter(A())").repeat(3, 100000)
- print "Test B:"
- print Timer("cnt.next()", "from gaap import B; cnt = iter(B())").repeat(3, 100000)
- print "Test Bs:"
- print Timer("cnt.next()", "from gaap import Bs; cnt = iter(Bs())").repeat(3, 100000)
- print "Test C:"
- print Timer("cnt.next()", "from gaap import C; cnt = iter(C())").repeat(3, 100000)
- print "Test Cs:"
- print Timer("cnt.next()", "from gaap import Cs; cnt = iter(Cs())").repeat(3, 100000)
advertising
Update the Post
Either update this post and resubmit it with changes, or make a new post.
You may also comment on this post.
Please note that information posted here will expire by default in one month. If you do not 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. All illegal activities will be reported and any information will be handed over to the authorities, so be good.