At 05:52 PM 6/24/2008, Dick Moores wrote:
At 05:35 PM 6/24/2008, Kent Johnson wrote:
On Tue, Jun 24, 2008 at 5:20 PM, Dick Moores <[EMAIL PROTECTED]> wrote:

> Basically, I'm not worried, just curious. Not about the small differences,
> but why did the use of the standard    if __name__ == '__main__'     result
> it such speed?

Because __name__ is not equal to "__main__", so you were basically
skipping the whole test.

Ah.

The most common cause of unexpected timing
results is tests that don't do what you think they do.

The test code is not run in the main module. You can dig into the
timeit module if you want the details.

OK, I'll dig.

While digging I came across this at the bottom of < http://docs.python.org/lib/node808.html>:

============================================================
To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:

def test():
    "Stupid test function"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__
import test")
    print t.timeit()

=============================================================

I thought I'd use this to compare the 2 ways of string concatenation. Ever since I began to learn Python I've been told that only one of these is the proper and efficient one to use, and especially so if the string to be stitched together is a very long one. So I set up two tests in separate scripts, with functions z1() and z2(). The string is 100,000 7-digit ints converted to strings and strung together, to make a  string of 700,000 digits. I thought this should be long enough to be a good test.

def z1():
    lst = []
    for y in range(100000):
        m = str(randint(1000000,
9999999)) 
        lst.append(m)
    return ''.join(lst)

if __name__=='__main__':
    from random import randint
    from timeit import Timer
    t = Timer("z1()", "from __main__ import
z1")
    print t.timeit(number=10)
"""
OUTPUTS:
9.95473754346
9.74315730072
"""

def z2():
    astr = ''
    for y in range(100000):
        m = str(randint(1000000,
9999999))  
        astr += m
    return astr

if __name__=='__main__':
    from random import randint
    from timeit import Timer
    t = Timer("z2()", "from __main__ import
z2")
    print t.timeit(number=10)
"""
OUTPUTS
10.8160584655
10.605619988
"""

The "proper" way did win, but by less than 10 percent.

I also tested z1() and z2() (slightly modified) with timeit at the
command line (see
<
http://py77.python.pastebin.com/f60e746fe>), with similar
results.

Dick Moores




_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to