[TIP] Interesting getattr pattern [was: Re: [issue5728] Support telling TestResult objects a test run has finished]

John Arbash Meinel john at arbash-meinel.com
Sat Apr 11 12:26:12 PDT 2009


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Raphael Marvie wrote:
> 
> John Arbash Meinel wrote:
> [snip.]
> 
>> I don't know if this is 100% valid but:
>>
>>
>> $ python -mtimeit -s'x = None' 'x is None'
>> 10000000 loops, best of 3: 0.0497 usec per loop
>>
>> $ python -mtimeit -s'y = object()' 'y is None'
>> 10000000 loops, best of 3: 0.0493 usec per loop
>>
>> $ python -mtimeit -s'def noop(): pass' 'noop()'
>> 10000000 loops, best of 3: 0.15 usec per loop
>>
>> So at least according to that, a no-op function call is 3x slower than
>> an 'is None' check.
> 
> Including its definition which should be done only once.

The def portion was in "-s" so it *is* done only once.

> 
>> Now maybe it is a bit more fair to add an if() check on that:
>>
>> $ python -mtimeit -s'x = None' 'if x is None: pass'
>> 10000000 loops, best of 3: 0.0486 usec per loop
>>
>> $ python -mtimeit -s'y = object()' 'if y is None: pass'
>> 10000000 loops, best of 3: 0.0512 usec per loop
> 
> The object() call is an instanciation, so it may cost more than an empty
> function (but I may be wrong).

Again "-s" is "setup" code which is done only one time, and then the non
'-s' portion is run repeatedly.

> 
> The goal of the noop() was to remove the test, so I would have compared:
> 
> $ python -mtimeit -s'x = None' 'if x is None: pass'
> 1000000 loops, best of 3: 0.208 usec per loope
> 
> $ python -mtimeit -s'y = object()'
> 10000000 loops, best of 3: 0.0906 usec per loop
> 
> which seems to encourage a the use of a noop() compare to a test if I
> follow you benchmark.

You aren't. This last one is testing the "actually do nothing" because
everything is in the setup. Put another way, your last test is:

$ python -mtimeit ''
10000000 loops, best of 3: 0.0906 usec per loop

If you want to test object creation:

$ python -mtimeit 'y = object()'
10000000 loops, best of 3: 0.15 usec per loop

Which happens to be exactly the same time as a no-op function call.
(Creating an object is calling its constructor which ... is a function
call.)

I can understand that you didn't understand the '-s XXX' argument, which
means "setup" and does it one time to create the variables, etc for the
loop you are testing.

Try:

python -m timeit --help

If you want more details.

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkng7tMACgkQJdeBCYSNAAPlLwCgnPJKR0Cz63+9j7ei+jaOFRpZ
D9oAnRYIXEXYL9rRE5UoOLrZR64uB3W5
=i4p/
-----END PGP SIGNATURE-----



More information about the testing-in-python mailing list