gentlejo
gentlejo

Reputation: 2710

Why python For in Loop is so slow?

I tested performance for in loop in python. It contains just loop and plus operations. But it takes about 0.5secs. How can I do it more faster?

import time

start_time = time.time()

val = -1000000
for i in range(2000000):
    val += 1

elapsed_time = time.time() - start_time

print(elapsed_time) # 0.46402716636657715

Upvotes: 2

Views: 1897

Answers (1)

Damien
Damien

Reputation: 684

Here are some optimizations:

  1. (Python 2) Use xrange() - this will return an iterator and will not need to first generate the list to allow you to iterate it. In Python 3, range() is essentially xrange()

  2. Wrap range(2000000) in an iter() function. I am not sure why, but I saw improvements during my tests

Upvotes: 2

Related Questions