Why does %timeit loop different number of times?
Asked Answered
S

3

27

On Jupter Notebook, i was trying to compare time taken between the two methods for finding the index with max value.

enter image description here

In the Image, the first function took, 1000 loops, and the second took 10000 loops, is this increase in loops due to the method itself OR Jupyter Just added more loops to get more accurate time per loop even though the second function maybe took 1000 only, is that the case?

Sherrell answered 28/7, 2017 at 13:34 Comment(0)
P
42

%timeit library will limit the number of runs depending on how long the script takes to execute.

The number of runs may be set with -n. Example:

%timeit -n 5000
df = pd.DataFrame({'High':[1,4,8,4,0]})

5000 loops, best of 3: 592 µs per loop
Pouter answered 28/7, 2017 at 13:40 Comment(4)
Thanks for the explanation.. I just thought I would mention it here for others..that there is a typo in the ipython docs.. which hasn't yet been corrected. The latest version for ipython defaults to 7 loops.. if -r is not mentioned.Lennielenno
I wanted to run timeit only once but %%timeit -n 1 is not working for me, but %%time worked for me.Coloring
what's the difference between -r and -n?Talion
@Talion as the docs point out: n - how many times to execute ‘statement’, r - how many times to repeat the timer (default 5).Pouter
O
11

use -r to limit the number of run's:

import time
%timeit -r1 time.sleep(2)
# 2 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

%timeit -r4 time.sleep(2)
# 2 s ± 800 µs per loop (mean ± std. dev. of 4 runs, 1 loop each)

%timeit time.sleep(2)
# 2 s ± 46.5 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
Odontology answered 19/2, 2020 at 14:15 Comment(1)
and you can put a space between -r and the number of runs for consistency with -nFernando
E
1

It has a built-in option -n: " Options: -n: execute the given statement times in a loop. If this value is not given, a fitting value is chosen."docs

So it choses the number of loops itself if not specified.

Latest quote (v8.26.0): "Options: -n: execute the given statement times in a loop. If is not provided, is determined so as to get sufficient accuracy.

-r: number of repeats , each consisting of loops, and take the average result. Default: 7 "

documentation screenshot

Enciso answered 28/7, 2017 at 13:40 Comment(2)
This doesn't seem to be true.. if you use -n1, it doesn't actually execute it once.. but 7 times.. Is there a reason why?Lennielenno
@Lennielenno you need %%timeit -n 1 -r 1, loops and repetitions are configured separately and repetitions default to 7.Elamite

© 2022 - 2024 — McMap. All rights reserved.