Skip to content

Instantly share code, notes, and snippets.

@porglezomp
Last active October 24, 2017 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porglezomp/bfb1b2a384b82511c769417db551539b to your computer and use it in GitHub Desktop.
Save porglezomp/bfb1b2a384b82511c769417db551539b to your computer and use it in GitHub Desktop.
python bytecode
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
Then, using dis.dis(fib)
CPython bytecode:
2 0 LOAD_CONST 3 ((0, 1))
2 UNPACK_SEQUENCE 2
4 STORE_FAST 1 (a)
6 STORE_FAST 2 (b)
3 8 SETUP_LOOP 30 (to 40)
10 LOAD_GLOBAL 0 (range)
12 LOAD_FAST 0 (n)
14 CALL_FUNCTION 1
16 GET_ITER
>> 18 FOR_ITER 18 (to 38)
20 STORE_FAST 3 (_)
4 22 LOAD_FAST 2 (b)
24 LOAD_FAST 1 (a)
26 LOAD_FAST 2 (b)
28 BINARY_ADD
30 ROT_TWO
32 STORE_FAST 1 (a)
34 STORE_FAST 2 (b)
36 JUMP_ABSOLUTE 18
>> 38 POP_BLOCK
5 >> 40 LOAD_FAST 1 (a)
42 RETURN_VALUE
PyPy bytecode:
2 0 LOAD_CONST 1 (0)
3 LOAD_CONST 2 (1)
6 STORE_FAST 1 (b)
9 STORE_FAST 2 (a)
3 12 SETUP_LOOP 36 (to 51)
15 LOAD_GLOBAL 0 (range)
18 LOAD_FAST 0 (n)
21 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
24 GET_ITER
>> 25 FOR_ITER 22 (to 50)
28 STORE_FAST 3 (_)
4 31 LOAD_FAST 1 (b)
34 LOAD_FAST 2 (a)
37 LOAD_FAST 1 (b)
40 BINARY_ADD
41 STORE_FAST 1 (b)
44 STORE_FAST 2 (a)
47 JUMP_ABSOLUTE 25
>> 50 POP_BLOCK
5 >> 51 LOAD_FAST 2 (a)
54 RETURN_VALUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment