Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

python - 为什么Python代码在函数中运行得更快?(Why does Python code run faster in a function?)

def main():
    for i in xrange(10**8):
        pass
main()

This piece of code in Python runs in (Note: The timing is done with the time function in BASH in Linux.)

(Python中的这段代码在其中运行(注意:计时是通过Linux中的BASH中的time函数完成的。))

real    0m1.841s
user    0m1.828s
sys     0m0.012s

However, if the for loop isn't placed within a function,

(但是,如果for循环未放在函数内,)

for i in xrange(10**8):
    pass

then it runs for a much longer time:

(那么它会运行更长的时间:)

real    0m4.543s
user    0m4.524s
sys     0m0.012s

Why is this?

(为什么是这样?)

  ask by thedoctar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Inside a function, the bytecode is

(在函数内部,字节码为)

  2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE        

At top level, the bytecode is

(在顶层,字节码是)

  1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE        

The difference is that STORE_FAST is faster (!) than STORE_NAME .

(区别在于STORE_FAST (!)比STORE_NAME更快(!)。)

This is because in a function, i is a local but at toplevel it is a global.

(这是因为在函数中, i是局部变量,但在顶层是全局变量。)

To examine bytecode, use the dis module .

(要检查字节码,请使用dis模块 。)

I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin .

(我可以直接反汇编该函数,但是要反汇编顶层代码,我必须使用compile Builtin 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...