Reputation: 446
I have a very simple test function that I need to capture its execution time using 'timeit' module, but I get an error
The function:
import timeit
def test1():
l = []
for i in range(1000):
l = l + [i]
t1 = timeit.Timer("test1()", "from __main__ import test1")
print(t1.timeit(number=1000))
The Error: C:\Python34\lib\timeit.py:186: in timeit timing = self.inner(it, self.timer) :3: in inner ??? E
ImportError: cannot import name 'test1' =========== 1 error in 0.03 seconds ==============
Can you guys help me with a solution?
Upvotes: 0
Views: 3730
Reputation: 517
I think there are couple of problems with your code. First for all make sure you can import timeit. And you have it as a module. For this, you can just run:
python -m timeit '"-".join(str(n) for n in range(100))'
If it execute fine then you sure have the timeit module.
Now regarding your question. I took the liberty to rewriting it in a cleaner way.
import timeit
def append_list():
num_list = []
for i in range(1000):
num_list.append(i)
print(timeit.timeit(stmt=append_list, number=1000)) #number is the number of repetion of the operation, in this case, 1000
# you can also run
print(timeit.timeit(stmt=append_list, number=1))
Now, the above could will do what you wanted to do, i.e calculate the amount of time required to append numbers from 1 to 1000 to the list.
Upvotes: 1