CS 301 Project Technical Blog
The general consensus about whether Python or C++ is slower, is that C++ is much more efficient. Many people have checked which language has better performance, but which just how much faster is C++, and is it always faster than Python? In this blog, I will show results of some experiments I did to answer these question, and will explore why C++ is generally faster than Python.
Syntax Differences
Python is well-known for how easy it is to write. Many argue that this makes it the better language to code with, but whether this difference really matters or not depends on personal preference and the coding situation that you are facing.
This code block is from a short program that converts any decimal number to the hexadecimal equivalent. The syntax is easy to read compared to the following block of C++ code that performs the same functions.
- Python uses dynamic types, C++ uses "declared" static types for variable declarations
- C++ has many more brackets and confusing characters for the user to interpret
- It is easier to make typos in development, adding debug time
As a result of these facts, the Python Interpreter Virtual Machine (PVM) acquires more overhead to interpret your code than a C++ compiler (such as g++) to compile its code. The PVM needs to figure out what data type each variable is, whereas the compiler is told by the developer what types are being used.
The PVM also cannot optimize code as the compiler can. Compilers will work to find the cleanest set of Assembly language instructions that will carry out your C++ code. Consequently, compilers will generate much more efficient instructions than any PVM.
Runtime Results
This table shows the results of the Fibonacci Sequence coded both recursively and not in both languages. Python's longer runtimes are due to the PVM working with the dynamic typing system and not being able to optimize the code. In a few smaller programs, such as simply printing, Python can outperform C++, but the results seen in the table above will hold true for any large program, and almost every small program.
Each language has its pros and cons, but, after doing this experiment, I recommend only distributing C++ code, unless you are using Python libraries that are designed for efficiency (as numPy). Python's clean syntax should be taken advantage of for making projects you do not intend to distribute or to build pseudocode for practicing programming concepts.
Comments
Post a Comment