timeit.timeit VS timeit.Timer.repeat - What is the best practice?
Asked Answered
D

1

11

I would like to optimize a function 'myfunc()'. I have several ways to write it, and I would like to check the fastest code. For that, we can use the 'timeit' module. But there are several ways to use it. The most obvious, and apparently the most used, is:

import timeit
timeit.Timer('myfunc()', "from __main__ import myfunc").timeit(100000)

which is similar to

timeit.timeit('myfunc()', "from __main__ import myfunc", number=100000)

But we can also used such code:

min(timeit.Timer('myfunc()', "from __main__ import myfunc").repeat(repeat=100000, number=1))*100000

I was expecting the last one to be the most accurate processing time, but it doesn't seem to be the most used code.

Could you help me to determine when it is better to use timeit.timeit, and when repeat is more appropriate?

Thanks in advance

Dag answered 7/5, 2019 at 12:12 Comment(2)
timeit is a "Convenience function to create Timer object and call timeit method." source:github.com/python/cpython/blob/master/Lib/timeit.py#L229Billposter
This is true. But this doesn't explain why the first command is more used than the third one (with 'repeat'), since the latter should be more accurate.Dag
F
0

timeit.timeit() is better suited for measuring the execution time of a single statement or function, while timeit.repeat() is better suited for measuring the execution time of a larger chunk of code and providing more stable results.

Foozle answered 23/8, 2023 at 0:5 Comment(1)
Can you provide some supporting evidence / a convincing argument for this? This is not necessarily an obvious conclusion from the information in the docs.Amari

© 2022 - 2024 — McMap. All rights reserved.