import time
time.time()
from time import time
time()
from time import time, sleep
start = time()
sleep(1)
end = time()
print(end - start)
start = time()
sum(range(10**6))
end = time()
print(end - start)
def timeit(f):
start = time()
f()
end = time()
return end - start
timeit(lambda: sum(range(10**6)))
def timeit(f):
duration = 0
for _ in range(10):
start = time()
f()
end = time()
duration += end - start
return duration / 10
timeit(lambda: sum(range(10**6)))
import timeit
timeit.timeit('sum(range(10**6))', number=100)
timeit.timeit(stmt='sorted(lst)',
setup='import random ; lst = [random.random() for _ in range(100)]',
number=100)
import random
def to_time(lst):
# do something interesting with the list
pass
timeit.timeit(stmt='to_time(lst)',
setup='lst = [random.random() for _ in range(100)]',
globals=globals(), # allows timeit to access functions we've defined in this notebook
number=1000)
timeit.timeit(stmt='lst[0]',
setup='import random; lst=[0] * 10**6')
timeit.timeit(stmt='lst[10**6-1]',
setup='import random; lst=[0] * 10**6')
import random
size = 10**3
times = [0] * size
lst = [0] * size
for _ in range(100):
for i in range(size):
times[i] += timeit.timeit(stmt='lst[{}]'.format(i),
globals=globals(),
number=10)
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(times, 'ro')
plt.show()
Accessing an element in a list by index always takes the same amount of time, regardless of position. I.e., indexing incurs a constant time delay.
How? A Python list uses an array as its underlying data storage mechanism. To access an element in an array, the interpreter:
Task: to locate an element with a given value in a list (array).
def index(lst, x):
for i in range(len(lst)):
if lst[i] == x:
return i
return None
lst = list(range(100))
index(lst, 10)
index(lst, 99)
index(lst, -1)
def index(lst, x):
for i in range(len(lst)):
if lst[i] == x:
return i
raise ValueError(x)
index(lst, 10)
index(lst, -1)
try:
print('Value found at', index(lst, -1))
except ValueError as e:
print('Value not found:', e)
import timeit
times = []
lst = list(range(1000))
for x in lst:
times.append(timeit.timeit(stmt='index(lst, {})'.format(x),
globals=globals(),
number=100))
import matplotlib.pyplot as plt
plt.plot(times, 'ro')
plt.show()
def index(lst, x):
# assume that lst is sorted!!!
low = 0
hi = len(lst)
mid = (low + hi) // 2
while lst[mid] != x and low <= hi:
if lst[mid] < x:
low = mid + 1
else:
hi = mid - 1
mid = (low + hi) // 2
if lst[mid] == x:
return mid
else:
raise ValueError(x)
lst = list(range(1000))
index(lst, 10)
index(lst, 999)
index(lst, -1)
for i in range(len(lst)):
assert(i == index(lst, i))
import timeit
times = []
lst = list(range(1000))
for x in lst:
times.append(timeit.timeit(stmt='index(lst, {})'.format(x),
globals=globals(),
number=1000))
import matplotlib.pyplot as plt
plt.plot(times, 'ro')
plt.show()
def index(lst, x):
# assume that lst is sorted!!!
low = 0
hi = len(lst)
mid = (low + hi) // 2
while lst[mid] != x and low <= hi:
if lst[mid] < x:
low = mid + 1
else:
hi = mid - 1
mid = (low + hi) // 2
if lst[mid] == x:
return mid
else:
return None # for testing!
import timeit
import random
times = []
for size in range(100, 10000, 100):
lst = list(range(size))
times.append(timeit.timeit(stmt='index(lst, -1)'.format(random.randrange(size)),
globals=globals(),
number=10000))
import matplotlib.pyplot as plt
plt.plot(times, 'ro')
plt.show()
import timeit
import random
times = []
for e in range(5, 20):
lst = list(range(2**e))
times.append(timeit.timeit(stmt='index(lst, -1)',
globals=globals(),
number=100000))
import matplotlib.pyplot as plt
plt.plot(times, 'ro')
plt.show()
import random
lst = list(range(1000))
random.shuffle(lst)
plt.plot(lst, 'ro')
plt.show()
def insertion_sort(lst):
for i in range(1, len(lst)):
for j in range(i, 0, -1):
if lst[j-1] > lst[j]:
lst[j-1], lst[j] = lst[j], lst[j-1] # swap
else:
break
insertion_sort(lst)
plt.plot(lst, 'ro')
plt.show()
import timeit
import random
times = []
for size in range(100, 5000, 100):
lst = list(range(size))
times.append(timeit.timeit(stmt='insertion_sort(lst)',
setup='random.shuffle(lst)',
globals=globals(),
number=1))
plt.plot(times, 'ro')
plt.show()