[Python-Dev] PEP 285: Adding a bool type

Stuart Bishop zen@shangri-la.dropbear.id.au
Fri, 5 Apr 2002 11:46:13 +1000


On Friday, April 5, 2002, at 01:06  AM, Guido van Rossum wrote:

>> On Thursday, April 4, 2002, at 02:22  PM, Stuart Bishop wrote:
>>
>>> On a side note, writing 'i or False and True' performs much better

I mean (i and True) or (i or False)

>>> than bool(i) in the test implementation, and flow control statements
>>> involving ints are perform much better than flow control using bool.
>>> Will there be a performance degredation in the final version, or
>>> can this be avoided?
>>
>> I fixed my test to not do a global lookup on True and flow control
>> is no longer slower.
>
> Do I take it that you were benchmarking with the Python class shown in
> the PEP?

No - I was benchmarking with the patch posted on Sourceforge (before
PEP285 was checked into CVS), patched into a CVS snapshot taken at
the same time.

  Casting  to bool using (x and True) or (x or False)  :  1.61
  Casting to bool using (bool)  :  2.68
  Flow control on explicit True  :  1.42
  Flow control on explicit 1  :  0.99
  Flow control on variable bound to True  :  1.02
  Flow control on variable bound to 1  :  0.99



import time

count = 1000000

def test1():
     ''' Casting  to bool using (x and True) or (x or False) '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         x = (i and True) or (i or False)
     end = time.clock()
     return end - start

def test2():
     ''' Casting to bool using (bool) '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         x = bool(i)
     end = time.clock()
     return end - start

def test3():
     ''' Flow control on explicit True '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         if True:
             pass
         else:
             pass
     end = time.clock()
     return end - start

def test4():
     ''' Flow control on explicit 1 '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         if 1:
             pass
         else:
             pass
     end = time.clock()
     return end - start

def test5(a = True):
     ''' Flow control on variable bound to True '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         if a: pass
         else: pass
     end = time.clock()
     return end - start

def test6(a = 1):
     ''' Flow control on variable bound to 1 '''
     nums = xrange(count)
     start = time.clock()
     for i in nums:
         if a: pass
         else: pass
     end = time.clock()
     return end - start

for f in (test1,test2,test3,test4,test5,test6):
     print f.__doc__,': ',f()

--
Stuart Bishop <zen@shangri-la.dropbear.id.au>
http://shangri-la.dropbear.id.au/