为什么在Python 3中“范围(1000000000000000(1000000000000001))”这么快?

假装没事ソ 提交于 2020-08-05 08:16:25

问题:

It is my understanding that the range() function, which is actually an object type in Python 3 , generates its contents on the fly, similar to a generator. 据我了解, range()函数实际上是Python 3中的一种对象类型 ,它像生成器一样动态生成其内容。

This being the case, I would have expected the following line to take an inordinate amount of time, because in order to determine whether 1 quadrillion is in the range, a quadrillion values would have to be generated: 在这种情况下,我本以为下一行会花费过多的时间,因为要确定1个四舍五入是否在该范围内,必须生成一个四舍五入值:

1000000000000000 in range(1000000000000001)

Furthermore: it seems that no matter how many zeroes I add on, the calculation more or less takes the same amount of time (basically instantaneous). 此外:似乎无论我添加多少个零,计算多少都花费相同的时间(基本上是瞬时的)。

I have also tried things like this, but the calculation is still almost instant: 我也尝试过这样的事情,但是计算仍然是即时的:

1000000000000000000000 in range(0,1000000000000000000001,10) # count by tens

If I try to implement my own range function, the result is not so nice!! 如果我尝试实现自己的范围函数,结果将不是很好!

def my_crappy_range(N):
    i = 0
    while i < N:
        yield i
        i += 1
    return

What is the range() object doing under the hood that makes it so fast? 使range()如此之快的对象是做什么的?


Martijn Pieters' answer was chosen for its completeness, but also see abarnert's first answer for a good discussion of what it means for range to be a full-fledged sequence in Python 3, and some information/warning regarding potential inconsistency for __contains__ function optimization across Python implementations. 选择Martijn Pieters的答案是因为它的完整性,但也可以看到abarnert的第一个答案 ,它很好地讨论了range在Python 3中成为完整序列的含义,以及有关__contains__函数优化可能存在不一致的一些信息/警告。 Python实现。 abarnert's other answer goes into some more detail and provides links for those interested in the history behind the optimization in Python 3 (and lack of optimization of xrange in Python 2). abarnert的其他答案更加详细,并为那些对Python 3优化背后的历史(以及Python 2中缺少xrange优化)感兴趣的人提供了链接。 Answers by poke and by wim provide the relevant C source code and explanations for those who are interested. pokewim的答案 感兴趣的人提供了相关的C源代码和说明。


解决方案:

参考一: https://stackoom.com/question/22DVr/为什么在Python-中-范围-这么快
参考二: https://oldbug.net/q/22DVr/Why-is-1000000000000000-in-range-1000000000000001-so-fast-in-Python-3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!