This article compares the execution efficiencies of the Python 2 and Python 3 pairs of collection-list
First I define a for_test function, and then use the Magic function of Ipython to perform the test of execution speed%timeit
%timeit automatically executes the objective function more than once to obtain a more accurate result.
in the process of testing, we found a strange problem, if you do not carry out the assignment, to get the elements alone, and the operation, Python 2 is more efficient than Python 3
If you add an assignment operation, Python 3 is more efficient than Python 2
But the strange thing is that if I test the function with%time, I find that Python 2 is more efficient than Python 3
run the test function only once with the%time test
def for_test (container):
for I, Num in enumerate (container):
num = num/5*10 + 12-8
container[i] = num
c Ontainer = List (range (1000000))
%time for_test (Container)
Python 2
Wall time:126 Ms # The results of multiple runs are 120-130 ms around
Wall time:129 ms Wall
time:128 ms
Python 3
Wall time:191 Ms # runs more than 160ms multiple times and can be seen as less efficient than Python 2
Wall time:176 ms
Wall time:183 ms
Run the test function multiple times with the%timeit test
def for_test (container):
for I, Num in enumerate (container):
num = num/5*10 + 12-8
container[i] = num
Co Ntainer = List (range (1000000))
%timeit for_test (Container)
Python 2
Loops, Best of 3:348 ms per loop # you can find significant test results relative to%time
Python 3
176 ms±5.96 ms Per loop (mean±std. Dev. of 7 runs, loops each)
if the test function only operates without assigning a value, the result is changed
%time
def for_test (container):
for I, Num in enumerate (container):
num = num/5*10 + 12-8
container = List (range (1000000))
%time For_test (Container)
Python 2
Wall time:98 ms
Wall time:96 ms
Wall time:97 ms
Pyhton 3
Wall time:142 ms
Wall time:138 ms
Wall time:175 ms
%timeit
def for_test (container):
for I, Num in enumerate (container):
num = num/5*10 + 12-8
container = List (range 10 00000))
%timeit for_test (Container)
Pyhton 2
Loops, Best of 3:96.7 ms Per loop
Python 3
145 ms±4.2 ms Per loop (mean±std. Dev. of 7 runs, loops each)
Summary
My guess is that%timeit's operating mechanisms in Python 2 and 3 may be different and result in a difference.