To evaluate the speed of execution, we will use the timeit library.
import timeit import numpy as np setup = """ import numpy as np tmp = np.empty(shape=(1, 100)) values = [i for i in xrange(100)] """ stmt1 = """tmp[0, :] = values""" stmt2 = """ for i, val in enumerate(values): tmp[0, i] = val """ time1 = timeit.Timer(setup=setup, stmt=stmt1) time2 = timeit.Timer(setup=setup, stmt=stmt2) print "numpy way :", time1.timeit(number=100000) print "Python way:", time2.timeit(number=100000)
You can test this, and you will notice that numpy loops are twice as fast:
- numpy way : 0.97758197784423828 - Python way: 2.1633858680725098
This is because there is a phase in which the integers in values (which are unlimited integers) are converted to 64-bit floats. To compare only loop speed, type conversion can be done previously in setup:
values = np.array([i for i in xrange(100)], dtype=np.float64)
Here is what I got:
numpy way : 0.131125926971 Python way: 2.64055013657
We notice that numpy loops are 20 times faster than Python loops.
You will find more information if you are looking for vectorized computing in Python ...
Taha
source share