为什么Python中的range()循环比使用while循环更快?

A. *_*ton 73 python performance benchmarking

前几天我做了一些Python基准测试,我发现了一些有趣的东西.下面是两个或多或少相同的循环.循环1大约需要循环2执行的两倍.

循环1:

int i = 0
while i < 100000000:
  i += 1
Run Code Online (Sandbox Code Playgroud)

循环2:

for n in range(0,100000000):
  pass
Run Code Online (Sandbox Code Playgroud)

为什么第一个循环这么慢?我知道这是一个微不足道的例子,但它引起了我的兴趣.range()函数有什么特别之处,它比以相同方式递增变量更有效吗?

kcw*_*cwu 144

看到python字节码的反汇编,你可能会得到一个更具体的想法

使用while循环:

1           0 LOAD_CONST               0 (0)
            3 STORE_NAME               0 (i)

2           6 SETUP_LOOP              28 (to 37)
      >>    9 LOAD_NAME                0 (i)              # <-
           12 LOAD_CONST               1 (100000000)      # <-
           15 COMPARE_OP               0 (<)              # <-
           18 JUMP_IF_FALSE           14 (to 35)          # <-
           21 POP_TOP                                     # <-

3          22 LOAD_NAME                0 (i)              # <-
           25 LOAD_CONST               2 (1)              # <-
           28 INPLACE_ADD                                 # <-
           29 STORE_NAME               0 (i)              # <-
           32 JUMP_ABSOLUTE            9                  # <-
      >>   35 POP_TOP
           36 POP_BLOCK
Run Code Online (Sandbox Code Playgroud)

循环体有10个操作

使用范围:

1           0 SETUP_LOOP              23 (to 26)
            3 LOAD_NAME                0 (range)
            6 LOAD_CONST               0 (0)
            9 LOAD_CONST               1 (100000000)
           12 CALL_FUNCTION            2
           15 GET_ITER
      >>   16 FOR_ITER                 6 (to 25)        # <-
           19 STORE_NAME               1 (n)            # <-

2          22 JUMP_ABSOLUTE           16                # <-
      >>   25 POP_BLOCK
      >>   26 LOAD_CONST               2 (None)
           29 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)

循环体有3个操作

运行C代码的时间比intepretor短得多,可以忽略.

  • 使用"dis"模块.在函数中定义代码,然后调用dis.disco(func .__ code__) (4认同)
  • 实际上,第一次拆卸中的循环体有10个操作(从位置32跳到9).在当前的CPython实现中,每个字节码的解释都会导致CPU中一个代价高昂的间接分支错误预测(跳转到下一个字节码的实现)的相当高的概率.这是当前CPython实现的结果,JIT由unladen swallow实现,PyPy和其他人很可能会失去这些开销.他们中最好的也能够进行类型专业化,达到一个数量级的加速. (2认同)

Geo*_*lly 32

range()在C中实现,而i += 1被解释.

使用xrange()可以使大数字更快.从Python 3.0开始与range()之前相同xrange().


Pet*_*ter 14

必须要说的是,while循环中存在大量的对象创建和破坏.

i += 1
Run Code Online (Sandbox Code Playgroud)

是相同的:

i = i + 1
Run Code Online (Sandbox Code Playgroud)

但是因为Python int是不可变的,所以它不会修改现有的对象; 相反,它创造了一个具有新价值的全新物体.它基本上是:

i = new int(i + 1)   # Using C++ or Java-ish syntax
Run Code Online (Sandbox Code Playgroud)

垃圾收集器也将进行大量的清理工作."对象创建很昂贵".


mCo*_*ing 12

我认为这里的答案比其他答案建议的更微妙,尽管它的要点是正确的:for 循环更快,因为更多的操作发生在 C 中,而更少的操作发生在 Python 中

更具体地说,在 for 循环情况下,C 中发生的两件事在 while 循环中由 Python 处理:

  1. 在 while 循环中,比较i < 100000000是在 Python 中执行的,而在 for 循环中,作业被传递给 的迭代器range(100000000),该迭代器在 C 中内部执行迭代(并因此进行边界检查)。

  2. 在 while 循环中,循环更新发生在 Python 中,而在 for 循环中,用 C 编写的i += 1迭代器再次执行(或)。range(100000000)i+=1++i

我们可以看到,正是这两者的结合,通过手动将它们添加回去以查看差异,使得 for 循环变得更快。

import timeit

N = 100000000


def while_loop():
    i = 0
    while i < N:
        i += 1


def for_loop_pure():
    for i in range(N):
        pass


def for_loop_with_increment():
    for i in range(N):
        i += 1


def for_loop_with_test():
    for i in range(N):
        if i < N: pass


def for_loop_with_increment_and_test():
    for i in range(N):
        if i < N: pass
        i += 1


def main():
    print('while loop\t\t', timeit.timeit(while_loop, number=1))
    print('for pure\t\t', timeit.timeit(for_loop_pure, number=1))
    print('for inc\t\t\t', timeit.timeit(for_loop_with_increment, number=1))
    print('for test\t\t', timeit.timeit(for_loop_with_test, number=1))
    print('for inc+test\t', timeit.timeit(for_loop_with_increment_and_test, number=1))


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

我尝试使用数字 100000000 作为文字常量,并将其作为N更典型的变量。

# inline constant N
while loop      3.5131139
for pure        1.3211338000000001
for inc         3.5477727000000003
for test        2.5209639
for inc+test    4.697028999999999

# variable N
while loop      4.1298240999999996
for pure        1.3526357999999998
for inc         3.6060175
for test        3.1093069
for inc+test    5.4753364
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在这两种情况下,时间都非常接近和while的差值。另请注意,在我们使用变量的情况下,重复查找 的值会出现额外的减慢,但不会。for inc+testfor pureNwhileNfor

如此琐碎的修改可以导致超过3 倍的代码加速,这确实很疯狂,但这就是适合您的 Python。当你根本可以在循环上使用内置函数时,甚至不要让我开始......