2

from python timeit module i want to check how much time does it take to print the following , how to do so,

import timeit
x = [x for x in range(10000)]
timeit.timeit("print x[9999]")
d=[{i:i} for i in x]
timeit.timeit("print d[9999]")

NameError: global name 'x' is not defined
NameError: global name 'd' is not defined
1
  • 1
    unrelated: you could also use the command-line interface: python -mtimeit -s'x = list(range(10000)); d = [{i:i} for i in x]' 'd[9999]' Commented Feb 16, 2015 at 23:53

2 Answers 2

4

Per the docs:

To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement

In your case, that would be e.g.:

timeit.timeit('print d[9999]', 
              setup='from __main__ import d')
Sign up to request clarification or add additional context in comments.

1 Comment

Not infinite, but timeit runs 1,000,000 times by default. Did you read the documentation at all?!
2

Here is an example of how you can do it:

import timeit

x = [x for x in range(10000)]
d = [{i: i} for i in x]

for i in [x, d]:
    t = timeit.timeit(stmt="print(i[9999])", number=100, globals=globals())
    print(f"took: {t:.4f}")

Output:

took: 0.0776
took: 0.0788

Please notice I added number=100, so it runs 100 times each test. By default it 1,000,000 times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.