为什么在Python中遍历range()比使用while循环更快? [英] Why is looping over range() in Python faster than using a while loop?

查看:167
本文介绍了为什么在Python中遍历range()比使用while循环更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.

循环1:

int i = 0
while i < 100000000:
  i += 1

循环2:

for n in range(0,100000000):
  pass

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

Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?

推荐答案

请参阅反汇编python字节码,您可能会得到更具体的想法

see the disassembly of python byte code, you may get a more concrete idea

使用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

循环主体有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

循环主体有3个操作

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

The time to run C code is much shorter than intepretor and can be ignored.

这篇关于为什么在Python中遍历range()比使用while循环更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆