[Tutor] List comprehension question

Richard D. Moores rdmoores at gmail.com
Sat Nov 13 08:25:38 CET 2010


On Fri, Nov 12, 2010 at 15:26, Steven D'Aprano <steve at pearwood.info> wrote:
> Richard D. Moores wrote:
>
>> OK, but why can't I do what the timeit doc suggests, only put 2 or
>> more functions in the file, as I do here:
>> <http://tutoree7.pastebin.com/84u1fkgA>
>>
>> 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()
>
>
> There's nothing wrong with that, except that running the test *once* (as you
> do) is subject to greater chance fluctuations than running it multiple
> times: change the last line to:
>
> print min(t.repeat())
>
> Note that you don't *have* to do this, the world will not end if you don't,
> but your timing results will be just a little more accurate if you do.
>
> If you want to time multiple functions, just use multiple timer objects:
>
> t1 = Timer("test()", "from __main__ import test")
> t2 = Timer("spam()", "from module import spam")
> t3 = Timer("ham()", "from module import ham")
>
>
>> I'm sorry, Steven, but could you revise this code to use repeat=5
>> instead of the for loop? I can't see how to do it.
>
> You don't need to choose repeat=5. The default is 3, but you can specify any
> number you like. I just like 5 :)

So I'll go with your 5.

>> if __name__=='__main__':
>>    from timeit import Timer
>>    for y in range(5):
>>        t = Timer("proper_divisors_sum1(500000)", "from __main__
>> import proper_divisors_sum")
>>        print round(t.timeit(number=10000),3)
>
> if __name__=='__main__':
>    from timeit import Timer
>    t = Timer("proper_divisors_sum(500000)",
>        "from __main__ import proper_divisors_sum")
>    best = t.repeat(number=10000, repeat=5)
>    print round(best, 3)

t.repeat(number=10000, repeat=5) is a list of the 5 times, not the
best of the 5. So I used
min(t.repeat(number=10000, repeat=5))

See <http://tutoree7.pastebin.com/>

Thanks very much, Steven!


More information about the Tutor mailing list