Reputation: 67
l = range(100)
%timeit [i**2 for i in l]
10000 loops, best of 3: 41.6 µs per loop
I am confused on how to explain the above output.
Upvotes: 1
Views: 3801
Reputation: 54303
[i**2 for i in l]
has been called by %timeit
10000 times.
Every time this line of code is being executed, %timeit
measures the time it took. Note that %timeit
doesn't always run an operation 10000 times. It runs it once and decides how many times the operation should be run. The goal is to have enough measurements while not needing 1 hour to give an estimate. If you try it with a larger l
, %timeit
might run only 1000 times.
Your computer might be doing some other operations at the same time (e.g. Browser, playing music, ...) so some executions might be really slow and shouldn't be taken into account.
%timeit
takes the 3 shortest executions out of the 10000 times, and displays their average. Your computer probably wasn't doing much during those executions, so the corresponding time might be representative of the time it would take if your computer was only concentrating on this task.
%
is used in order to tell iPython it's a iPython command, not a Python command. If you try it in normal Python console, it will fail with a SyntaxError
. You can also type %history
in iPython.
Upvotes: 4
Reputation: 7534
That is the default behavior of %timeit
, it performs multiple runs in order to attain more robust results.
l = range(100)
%timeit [i**2 for i in l]
10000 loops, best of 3: 41.6 µs per loop
No. of loops executed is 1000, and it gives you the best out of three execution time.
Upvotes: 0