For while () loop speed

Hello, I think the two fragments below should do the same:

for divisor in range(2, 21): if sample % divisor != 0: break 

The first fragment, I use sample divided by a number from 2 to 20, if any of them gives a remainder! = 0, then I will break and try sample += 1 (codes omitted)

 if all(sample % divisor == 0 for divisor in range(2, n2+1)): return sample 

In the second fragment, I will return the sample if all() returns with True , otherwise I will try sample += 1 (codes are omitted)

The second fragment was found twice as slow as the first. I don’t understand when python evaluates all (), if the same False was found in the iteration, it should immediately return False for all (), and not finish the whole iteration, right?

So why is the second fragment slower than the first?

-1
source share
1 answer

Here is your hint:

 >>> (sample % divisor == 0 for divisor in range(2, n2+1)) <generator object <genexpr> at 0x10ead7a00> 

Your code generates the xp gene and requires all to call the next method again on this genex.

This is an unavoidable performance hit in a for loop, in which there are no function calls. See Also Python: why list comprehension is slower than for a loop .

+4
source

Source: https://habr.com/ru/post/1276198/


All Articles