26

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?

3 Answers3

39

%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
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
  • 2
    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. – alpha_989 Jun 16 '18 at 19:28
  • I wanted to run timeit only once but %%timeit -n 1 is not working for me, but %%time worked for me. – Kharthigeyan Mar 25 '21 at 22:26
  • what's the difference between -r and -n? – haneulkim Dec 23 '21 at 23:57
  • 1
    @haneulkim as the docs point out: `n` - how many times to execute ‘statement’, `r` - how many times to repeat the timer (default 5). – Bharath M Shetty Dec 25 '21 at 08:22
10

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)
Savrige
  • 3,352
  • 3
  • 32
  • 38
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.

Krishal
  • 43
  • 8
  • 1
    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? – alpha_989 Jun 16 '18 at 18:19
  • 4
    @alpha_989 you need `%%timeit -n 1 -r 1`, loops and repetitions are configured separately and repetitions default to 7. – lumbric Sep 25 '19 at 14:14