I'm iterating 4 million times (for a project). This is taking forever to do. I was wondering how I can go faster.
numbers = [0,1]
evenNumbers = []
y = 0
l = 0
for x in range (1,4000000):
l = numbers[x-1] numbers[x]
numbers.append(l)
for k in numbers:
if k % 2 ==0:
evenNumbers.append(k)
for n in evenNumbers:
y = n
print(y)
CodePudding user response:
This is going to be very slow regardless due to the how big the numbers are getting, but you can speed it up significantly by just not storing all the intermediate values:
m, n = 0, 1
y = 0
for _ in range(1, 4000000):
m, n = n, m n
if n % 2 == 0:
y = n
print(y)
CodePudding user response:
You should just compare the time it takes for each function here to complete, as they are the three different ways that most would approach iteration.
import time
def foreach(arr):
for i in range(len(arr)):
print(arr[i])
def forin(arr):
for i in arr:
print(i)
def whileloop(arr):
i = 0
while i < len(arr):
print(arr[i])
i = 1
def main():
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
start = time.time()
foreach(arr)
end = time.time()
print("foreach: ", end - start)
start = time.time()
forin(arr)
end = time.time()
print("forin: ", end - start)
start = time.time()
whileloop(arr)
end = time.time()
print("whileloop: ", end - start)
if __name__ == "__main__":
main()