Skip to content

Instantly share code, notes, and snippets.

@anupam-io
Created February 10, 2021 06:28
Show Gist options
  • Save anupam-io/cc8add6c013c2357a5036a22fc0dd51a to your computer and use it in GitHub Desktop.
Save anupam-io/cc8add6c013c2357a5036a22fc0dd51a to your computer and use it in GitHub Desktop.
Testing various approaches of iterating through python lists using indexes
from time import time
n = 10**4
arr = [i for i in range(n)]
def test_fun(i):
# some compuatations
a =0
b =0
a+=arr[i]*arr[i]*arr[i]*arr[i]*arr[i]*arr[i]
b+=arr[i]+arr[i]+arr[i]+arr[i]+arr[i]+arr[i]
a+=arr[i]*arr[i]*arr[i]*arr[i]*arr[i]*arr[i]
b+=arr[i]+arr[i]+arr[i]+arr[i]+arr[i]+arr[i]
a+=arr[i]*arr[i]*arr[i]*arr[i]*arr[i]*arr[i]
b+=arr[i]+arr[i]+arr[i]+arr[i]+arr[i]+arr[i]
a+=arr[i]*arr[i]*arr[i]*arr[i]*arr[i]*arr[i]
b+=arr[i]+arr[i]+arr[i]+arr[i]+arr[i]+arr[i]
c = a+b
arr[i] = c
# Approach 1: The standard and most optmimized way[in python]
st = time()
for i in range(n):
test_fun(i)
fin = time()
print('Time for approach 1: ', fin-st)
# Approach 2
st = time()
i = 0
while(True):
try:
test_fun(i)
i+=1
except:break
fin = time()
print('Time for approach 2: ', fin-st)
# Approach 3
st = time()
i = 0
while i!=n:
test_fun(i)
i+=1
fin = time()
print('Time for approach 3: ', fin-st)
# Approach 4
st = time()
i = 0
while True:
test_fun(i)
i+=1
if i==n:break
fin = time()
print('Time for approach 4: ', fin-st)
@anupam-io
Copy link
Author

Results on colab:

Time for approach 1:  0.030594587326049805
Time for approach 2:  0.03899192810058594
Time for approach 3:  0.2079174518585205
Time for approach 4:  4.617676734924316

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment