Python is an interpreted programming language. However, similar to Java, it compiles the source code to byte-code, which will improve the code performance. Java compiles the source code (*.java) into byte-code (*.class) in order to gain performance improvements. Python, similarly, will compile *.py to *.pyc. The bytecode is platform independent, which means you can write once, compile once, and run everywhere.
Python provides a dis module which can take the function, class, method, or code object as its single argument and provides a more human-readable source code in the level of assembler. You can also run the disassembler from the command line. It compiles the given script and prints the disassembled byte codes to the STDOUT.
The following shows the basic example of the Fibonacci computation in the recursive Python function.
#!/usr/bin/env python def f(n): if n == 1: return 1 elif n == 0: return 0 else: return f(n - 1) + f(n - 2) for i in xrange(1, 20): print f(i) import dis dis.dis(f)
It outputs the following:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 4 0 LOAD_FAST 0 (n) 3 LOAD_CONST 1 (1) 6 COMPARE_OP 2 (==) 9 POP_JUMP_IF_FALSE 16 5 12 LOAD_CONST 1 (1) 15 RETURN_VALUE 6 >> 16 LOAD_FAST 0 (n) 19 LOAD_CONST 2 (0) 22 COMPARE_OP 2 (==) 25 POP_JUMP_IF_FALSE 32 7 28 LOAD_CONST 2 (0) 31 RETURN_VALUE 9 >> 32 LOAD_GLOBAL 0 (f) 35 LOAD_FAST 0 (n) 38 LOAD_CONST 1 (1) 41 BINARY_SUBTRACT 42 CALL_FUNCTION 1 45 LOAD_GLOBAL 0 (f) 48 LOAD_FAST 0 (n) 51 LOAD_CONST 3 (2) 54 BINARY_SUBTRACT 55 CALL_FUNCTION 1 58 BINARY_ADD 59 RETURN_VALUE 60 LOAD_CONST 0 (None) 63 RETURN_VALUE
This provides an easy tool to analyse your Python code for speed bottlenecks.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Variable Scopes in Javascript
Next Post: Multiplication Operator in Python