List vs numpy
natamacm
Posted on May 9, 2020
Python supports lists, so why would you use numpy?
Technically they're both Python lists, but creating them may be different in times of performance. Let's put it to the test.
First we test how long it takes to add a lot of numbers to a list c[]
and measure that.
Because we use Python lists we don't need any modules other than the time
module.
import time
start = time.clock()
a = range(10000000)
b = range(10000000)
c = []
for i in range(len(a)):
c.append(a[i] + b[i])
elapsed = (time.clock() - start)
print("List Time used:",elapsed)
List Time used: 4.712518
Then we measure how long that takes with numpy.
The module numpy
should be installed on your computer or virtual environment.
You can install it with pip if you don't have it installed.
import time
start = time.clock()
import numpy as np
a = np.arange(10000000)
b = np.arange(10000000)
c = a + b
elapsed = (time.clock() - start)
print("Time used:",elapsed)
Time used: 0.693733
These measurements are on my pc, so on your pc they may be different. So it can be a lot faster to use numpy when creating lists.
In this case it was almost 10 times faster, so if you want to increase performance it may be as simple as switching to numpy.
Posted on May 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.