NotAName
NotAName

Reputation: 4347

timeit takes forever to time a simple operation

Not sure what I'm doing wrong here. Just trying to compare lookup speeds of list and dict, but timeit just takes forever to get results.

from timeit import timeit

foo = list(range(10000000))
bar = {x:0 for x in range(10000000)}

timeit('5000000 in foo', globals=globals())

I also tried not using globals but passing initialisation statements to setup within timeit, but same result.

Am I doing something wrong here?

Upvotes: 1

Views: 54

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195553

Put number= parameter to timeit() function to limit number of executions:

from timeit import timeit

foo = list(range(10_000_000))
bar = {x:0 for x in range(10_000_000)}

print( timeit('5000000 in foo', globals=globals(), number=1) )

Prints:

0.0755848770004377

Upvotes: 3

Related Questions