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)