[英]elif versus else if; is one faster than the other and looking at python assembly
Are these two code snippets exactly the same (like they would be in c++) or will they both produce slightly different running times? 这两个代码片段是完全相同的(就像它们在c ++中一样)还是会产生稍微不同的运行时间?
first) 第一)
x = 'hello joe'
if x == 'hello':
print('nope')
elif x == 'hello joe':
print(x)
second) 第二)
x = 'hello jo'
if x == 'hello':
print('nope')
else:
if x == 'hello joe':
print(x)
I wanted to find out myself but I am not sure how I might go about watching this code run in its assembly form in real time. 我想找出自己,但我不确定如何实时观看这个代码以汇编形式运行。 Which brings me to my second question: how might I see the compiled assembly instructions that are made when I compile a Python program?
这让我想到了第二个问题:我如何看到编译Python程序时编译的汇编指令?
First, let's put your code(s) in a function 首先,让我们将您的代码放在一个函数中
def func(): # line 1
x = 'hello joe' # line 2
if x == 'hello': # line 4
print('nope') # line 5
else: # line 6
if x == 'hello joe': # line 7
print(x) # line 8
now disassemble with that (using CPython 3.4): 现在反汇编(使用CPython 3.4):
import dis
dis.dis(func)
we get: 我们得到:
2 0 LOAD_CONST 1 ('hello joe')
3 STORE_FAST 0 (x)
4 6 LOAD_FAST 0 (x)
9 LOAD_CONST 2 ('hello')
12 COMPARE_OP 2 (==)
15 POP_JUMP_IF_FALSE 31
5 18 LOAD_GLOBAL 0 (print)
21 LOAD_CONST 3 ('nope')
24 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
27 POP_TOP
28 JUMP_FORWARD 25 (to 56)
7 >> 31 LOAD_FAST 0 (x)
34 LOAD_CONST 1 ('hello joe')
37 COMPARE_OP 2 (==)
40 POP_JUMP_IF_FALSE 56
8 43 LOAD_GLOBAL 0 (print)
46 LOAD_FAST 0 (x)
49 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
52 POP_TOP
53 JUMP_FORWARD 0 (to 56)
>> 56 LOAD_CONST 0 (None)
59 RETURN_VALUE
now change to elif:
现在改为
elif:
2 0 LOAD_CONST 1 ('hello joe')
3 STORE_FAST 0 (x)
4 6 LOAD_FAST 0 (x)
9 LOAD_CONST 2 ('hello')
12 COMPARE_OP 2 (==)
15 POP_JUMP_IF_FALSE 31
5 18 LOAD_GLOBAL 0 (print)
21 LOAD_CONST 3 ('nope')
24 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
27 POP_TOP
28 JUMP_FORWARD 25 (to 56)
6 >> 31 LOAD_FAST 0 (x)
34 LOAD_CONST 1 ('hello joe')
37 COMPARE_OP 2 (==)
40 POP_JUMP_IF_FALSE 56
7 43 LOAD_GLOBAL 0 (print)
46 LOAD_FAST 0 (x)
49 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
52 POP_TOP
53 JUMP_FORWARD 0 (to 56)
>> 56 LOAD_CONST 0 (None)
59 RETURN_VALUE
The only differences are the line numbers. 唯一的区别是行号。
else: # line 6
if x == 'hello joe': # line 7
becomes (and shifts the rest as well) 成为(并转移其余部分)
elif x == 'hello joe': # line 6
There are as many instructions in both versions. 两个版本中都有尽可能多的指令。 The
else
and if
keywords in that case seem to have been converted exactly the same way as elif
. else
和if
在这种情况下的关键字似乎与elif
完全相同。 Not guaranteed in all implementations. 并非所有实现都保证。 Personally I'd stick to the shortest code (
elif
) because it's more "meaningful" and if a code should be faster, it would probably be that one. 就个人而言,我坚持使用最短的代码(
elif
),因为它更“有意义”,如果代码应该更快,那么它可能就是那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.