简体   繁体   中英

Timeit module -passing arguments to python timeit module

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

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 eg:

timeit.timeit('print d[9999]', 
              setup='from __main__ import d')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM