4 Main Reasons Why I am moving to C++ from Python

I often receive questions about the advantages and disadvantages of different programming languages. Among the most frequently compared are C++ and Python. Now I’ve been a Python fan for a long time. Since I started working as a student research assistant (in the automobile industry), I’ve been using Python for my applications. I’ve enjoyed programming in Python very much and I’ve found C++ a little more overwhelming than Python. Even in my opinion, it takes relatively more lines of code in C++ than in Python to do the same thing.

When it comes to Python projects, I have also practiced several that can be useful in everyday life, such as getting data through the CAN bus from a car, measuring object acceleration, accessing GNSS data of a vehicle, and even a bicycle model for the self-driving program.

c++

However, it is time for me to limit Python and move my preference more towards C++ in my applications. In this post, I will go through four significant reasons for my preference for C++ over Python. This can also help you understand why C++ remains an indispensable language for many developers.

[It’s 2024 and taking offense is a trend, so just a quick note to say that this post is purely my own opinion and a matter of preference. I’m not trying to convey any negative messages against Python programming language at all. So give your chest a rest and have fun!]

1. Performance and Efficiency

One of the most notable advantages of C++ over Python is its superior performance and efficiency. Even my own experience confirms that Python lacks the speed in runtime application. I work in automobile industry and the time precision required in developing automated/autonomous vehicles is immensely high (we are talking milliseconds here).

For example, I once wrote a small application for Tesla that needed to log every time a driver activated the Autopilot feature. The application needed to be precise, meaning it needed the exact timestamp of when the feature was activated. However, during testing, the program logged data a few hundred milliseconds after the Autopilot was activated. The time inaccuracy was clear and noticeable. The same application, written in C++, solved the delay problem.

Compared to Python, C++ is superior in performance and efficiency. It is a statically typed, compiled language, which means the code is converted directly into machine language before execution. This results in faster execution times and more efficient use of system resources. Python, on the other hand, is an interpreted, dynamically typed language. This difference leads to slower execution times for Python programs, especially for computationally intensive tasks.

2. Memory Management

One feature of C++ that I personally like is the control of memory through pointers. I’ll be honest; I had trouble understanding pointers at first, but eventually I did, and I immediately fell in love with the feature. Memory management through pointers and manual allocation/deallocation of memory using operators like new and delete allows developers to optimize memory usage and manage system resources more effectively. Below is an example code snippet of the same:

#include <iostream>

int main() {
    int* ptr = new int;
    *ptr = 10;
    std::cout << "Value: " << *ptr << std::endl;
    delete ptr; // Manually freeing memory
    return 0;
}

Python handles memory management automatically through garbage collection. While this simplifies development, it introduces overhead that can impact performance.

ptr = 10
print(f"Value: {ptr}")
# No need to manually free memory

3. System-Level Programming

If you are not already aware, I am an automobile engineer with interest and skills in programming. So codes and cars are basically my area of work and interest. To implement certain vehicle control algorithms, the actuators are controlled over the ECU and this required system-level programming.

C++ excels in system-level programming due to its low-level capabilities. It allows direct manipulation of hardware and system resources, making it ideal for developing operating systems, drivers, embedded software, and even IoT applications.

A very fine example of this is a very basic LED control exercise using buttons over Arduino. Of course, an LED can be controlled by importing the Arduino Pin library and using the methods. However, as we are interested in system-level programming, here’s a different and a BETTER way to do the same:

#include <avr/io.h>
#include <stdio.h>

// Function to configure buttons and LEDs
void setup() {
    /* Configure buttons as input */
    // Configure button connected to PE4 as input (for green LED)
    DDRE &= ~(1 << DDE4);
    // Configure button connected to PE5 as input (for red LED)
    DDRE &= ~(1 << DDE5);

    /* Configure LEDs as output */
    // Set PA1 as output (for green LED)
    DDRA |= (1 << DDA1);

    // Set PA2 as output (for red LED)
    DDRA |= (1 << DDA2);
}

void loop() {
    while (true) {
        // Turn on the green LED if the button connected to PE4 is pressed
        if (PINE & (1 << PINE4)) {
            PORTA |= (1 << PA1);
        } else {
            // Turn off the green LED if the button is not pressed
            PORTA &= ~(1 << PA1);
        }

        // Turn on the red LED if the button connected to PE5 is pressed
        if (PINE & (1 << PINE5)) {
            PORTA |= (1 << PA2);
        } else {
            // Turn off the red LED if the button is not pressed
            PORTA &= ~(1 << PA2);
        }
    }
}

int main() {
    setup();
    loop();

    return 0;
}

Don’t worry if you do not understand the code. To briefly explain, the PORT and the PIN are registers of Arduino Mega 2560 where the push buttons and LEDs are connected. Such system-level programming allows us to directly control the input (push buttons) and the output (LEDs) using bits and bytes. This works much faster in runtime than the traditional method of declaring and saving the state in variables. Below is the video of the output of the above code.

Python lacks the same level of access to system-level resources.

4. Concurrency and Parallelism

Concurrency and parallelism are critical for modern applications to leverage multi-core processors effectively. C++ offers robust support for multithreading and parallel programming through libraries like the C++ Standard Library.

#include <iostream>
#include <thread>

void print_message(const std::string& message) {
    std::cout << message << std::endl;
}

int main() {
    std::thread t1(print_message, "Hello from thread 1");
    std::thread t2(print_message, "Hello from thread 2");
    
    t1.join();
    t2.join();
    return 0;
}

Python’s Global Interpreter Lock (GIL) can be a significant bottleneck for CPU-bound applications.

import threading

def print_message(message):
    print(message)

t1 = threading.Thread(target=print_message, args=("Hello from thread 1",))
t2 = threading.Thread(target=print_message, args=("Hello from thread 2",))

t1.start()
t2.start()

t1.join()
t2.join()

While both languages support multithreading, C++ is often more efficient due to the absence of the GIL.

Summary

In this blog, I stated 4 reasons how C++ outpowers Python in certain areas. Python, however, still holds dominance in certain areas like developing machine learning models, certain IoT applications, data analysing, data processing etc. And this certainly does not mean that one should completely let go of Python. I, of course, won’t stop using Python wherever necessary. If I have to work on data processing or build a machine learning model, I would gladly switch to Python. On the other hand, when it comes to developing system-level program, C++ is the language I will look up to.

Next, I am going to start 100 Days of C++ series where I will document my journey and the topics I learn in C++. If you are interested, follow me on Instagram as I will also publish posts on the same. This way, you will never miss a day and will keep up with the progress.

If you enjoyed this post, do follow me on my social media as a sign of appreciation.

I also have a newsletter program where at the end of every month, I remind my followers of the posts they might have missed. And if you are reading this, this certainly means that you want to stay updated with the latest posts, don’t you? And it’s completely FREE!!! So why do join today?

This Post Has One Comment

Leave a Reply