When I try to run this code I am supposed to get values for the time time it took the program to located[42] but I keep getting an erroe
import random
import time
ranges = [1000, 10000, 100000, 1000000]
dict_times = []
index_times = []
sort_times = []
for i in ranges:
L = random.sample(range(i), i)
d = dict(zip(L,L))
#time for dict ------
#start the time here
start = time.time()
v = d[42]
#end the time here
end = time.time()
dict_times.append(end-start)
#time for index ------
#start the time here
start = time.time()
ind = L.index(42)
#end the time here
end = time.time()
index_times.append(end-start)
#time for sort -----
#start the time here
start = time.time()
L = sorted(L)
#end the time here
end = time.time()
sort_times.append(end-start)
print('Times for dictionary lookup:', dict_times, end="\n\n")
print('Times for list lookup:', index_times)
index_ratios = [round(index_times[i]/index_times[i-1], 2) for i in range(1, len(index_times))]
print('List lookup Ratios:', index_ratios, end="\n\n")
print('Times for list sort:', sort_times)
sort_ratios = [round(sort_times[i]/sort_times[i-1], 2) for i in range(1, len(sort_times))]
print('List sort Ratios:', sort_ratios, end="\n\n")
list_sort_over_index = [round(sort_times[i]/index_times[i], 2) for i in range(len(sort_times))]
print('List sort over list lookup:', list_sort_over_index, end="\n\n")
The error I get is: line 57, in index_ratios = [round(index_times[i]/index_times[i-1], 2) for i in range(1, len(index_times) The full error I get is:
runfile('C:/Users/sanil/OneDrive/Desktop/Business App Developement/hw9/turnin/hw09.py.py', wdir='C:/Users/sanil/OneDrive/Desktop/Business App Developement/hw9/turnin', current_namespace=True) Times for dictionary lookup: [0.0, 0.0, 0.0, 0.0]
Times for list lookup: [0.0, 0.0, 0.0, 0.03130626678466797] Traceback (most recent call last):
File "C:\Users\sanil\OneDrive\Desktop\Business App Developement\hw9\turnin\hw09.py.py", line 57, in index_ratios = [round(index_times[i]/index_times[i-1], 2) for i in range(1, len(index_times))]
File "C:\Users\sanil\OneDrive\Desktop\Business App Developement\hw9\turnin\hw09.py.py", line 57, in index_ratios = [round(index_times[i]/index_times[i-1], 2) for i in range(1, len(index_times))]
ZeroDivisionError: float division by zero I am running this code in sypder, am I missing any plug ins in the application, no matter how many times I run the code I am getting the same error
CodePudding user response:
Try using time.perf_counter()
by replacing all instances of time.time()
in your code with time.perf_counter()
.
From the time.time()
documentation,
[n]ote that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.
That probably explains why you get 0s as you are subtracting low precision times over very fast operations.