If python interpreter is written in C then why is python slower than C?

If python interpreter is written in C then why is python slower than C? by Keith Derrick

Answer by Keith Derrick:

It’s the difference between a compiled and interpreted language. It’s also the difference between dynamic and static typing.

Consider two hello world programs

// C
 
#include <stdio.h>
int main() {
  printf("Hello world\n");
  return 0;
} 

# Python
print("Hello world")

The C program is “bigger” right? More characters, more lines, etc. Well, that’s the source code. But get each program in a state where you can run them. The python is already there. But for the C you need to compile and link it first to make an executable.

At this point, the Python file hasn’t gotten any smaller. But the C program has been reduced to some boilerplate code to start and stop the program, a PUSH, a CALL, a MOVE, and a RETURN (oversimplified, but good enough).

Now run them

$ time c_hello_world
Hello World 

real	0m0.002s
user	0m0.001s
sys	0m0.001s
$ python ./hello.py
Hello World

real	0m0.034s
user	0m0.028s
sys	0m0.006s

Tiny differences, (about 32 thousandths of a second) but this is a tiny toy program.

Consider what happens when you hit return (again simplified).

For the C program:

  • The shell creates a new process
  • the new process loads a small binary file and calls main()
  • the process finishes

For the python program

  • The shell creates a new process
  • The new process loads a very big binary file (the python interpreter)
  • The interpreter does a lot of initialization etc
  • The interpreter opens the python source file
  • It reads the first line
  • It parses the first line
  • It creates the necessary object to represt the string “Hello World”
  • It then calls a C routine (called something like “print”)
  • The C routine inspects the Python dynamically typed object it is passed to figure out what type it is and work out how to print it.
  • The C routine calls other C routines to actually print the line of text and returns to the interpreter
  • The interpreter tries to read the next line of the python file and finds it is at the end
  • The interpeter does lots of clean up, releasing memory, closing files, etc
  • The interpreter exits
  • The process finishes.

Much of this has to be repeated for every line of code in a python script.

If python interpreter is written in C then why is python slower than C?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s