[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Quick question from newbie



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

David Muffley wrote:
> If I recall correctly, the syntax
> 
> if 1 <= i <= 9
> 
> runs slower than the syntax
> 
> if i <= 9 and i >= 1
> 
> Somewhere around 10% slower.  If you use psyco, it goes about 40% slower!

Hi,

Please see attached. Running it on my system gives:

Dummy, True:  [0.41186404228210449, 0.37368297576904297,
0.37651586532592773]
Dummy, False:  [0.37883090972900391, 0.3735659122467041,
0.37064504623413086]
Split, True:  [0.50581693649291992, 0.50107502937316895,
0.49922895431518555]
Split, False:  [0.50350499153137207, 0.50108599662780762,
0.50019001960754395]
Single, True:  [0.51301288604736328, 0.50690793991088867,
0.50961399078369141]
Single, False:  [0.51408696174621582, 0.50688409805297852,
0.5071709156036377]
Muffley, True:  [0.54985213279724121, 0.54391098022460938,
0.54220199584960938]
Muffley, False:  [0.43162894248962402, 0.42434787750244141,
0.42731213569641113]

"True" means running with i=5. "False" means i=10. Interestingly, your
(IMHO unusual) syntax runs slower when i=5, but faster when i=10. I
would guess that it is running faster because i = 10 fails the first
part of the "and" expression, and the second part need not be
evaluated. I cannot exactly guess why it should run slower, since it
should be doing as much work as the "split" case and no more.

Between the two more common variants of:

1 <= i <= 9

and

1 <= i and i <= 9

There appear to be no difference (or a very small difference, much
less than 10%).

Ethan
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFHLSDThRlgoLPrRPwRAhGUAJ4u5arJCe44vBDMX8lMp+GpOwzwpACfUusP
X2zwJEGll9IBXYYFSabMm3M=
=YDJ7
-----END PGP SIGNATURE-----
import timeit

def f0(i):
    return

def f1(i):
    return 1 <= i and i <= 9

def f2(i):
    return 1 <= i <= 9

def f3(i):
    return i <= 9 and i >= 1

N = 1000000

t = timeit.Timer("f0(5)", "from __main__ import f0")
print "Dummy, True: ", t.repeat(3, N)

t = timeit.Timer("f0(10)", "from __main__ import f0")
print "Dummy, False: ", t.repeat(3, N)

t = timeit.Timer("f1(5)", "from __main__ import f1")
print "Split, True: ", t.repeat(3, N)

t = timeit.Timer("f1(10)", "from __main__ import f1")
print "Split, False: ", t.repeat(3, N)

t = timeit.Timer("f2(5)", "from __main__ import f2")
print "Single, True: ", t.repeat(3, N)

t = timeit.Timer("f2(10)", "from __main__ import f2")
print "Single, False: ", t.repeat(3, N)

t = timeit.Timer("f3(5)", "from __main__ import f3")
print "Muffley, True: ", t.repeat(3, N)

t = timeit.Timer("f3(10)", "from __main__ import f3")
print "Muffley, False: ", t.repeat(3, N)