Created
February 10, 2021 06:28
-
-
Save anupam-io/cc8add6c013c2357a5036a22fc0dd51a to your computer and use it in GitHub Desktop.
Testing various approaches of iterating through python lists using indexes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on colab: