C++ vs. Python: A Performance Comparison using an Example

Introduction

We will use the example of computing the factorial of a large number to compare the performance of C++ and Python. The factorial of a number is the product of all the positive integers up to and including that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

Recursive Algorithm in Python

To compute the factorial of a large number, we will use a recursive algorithm. The algorithm will call itself with a smaller number until it reaches the base case of 1. Here is the recursive algorithm in Python.

def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n-1)

Recursive Algorithm in C++

int factorial(int n) {
    if (n == 1) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}

Performance Comparison

To compare the performance of C++ and Python, we will compute the factorial of a large number using both languages. We will use the number 100 for this example, which has a factorial of 100 x 99 x 98 x ... x 2 x 1.

Here is the Python code to compute the factorial of 100.

import time

start = time.time()

result = factorial(100)

end = time.time()

print("Factorial of 100: ", result)
print("Time taken: ", end - start)

And here is the C++ code to compute the factorial of 100.

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

int main() {
    auto start = high_resolution_clock::now();

    int result = factorial(100);

    auto end = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(end - start);

    cout << "Factorial of 100: " << result << endl;
    cout << "Time taken: " << duration.count() << " microseconds" << endl;

    return 0;
}

When we run the Python code, it takes approximately 0.025 seconds to compute the factorial of 100. On the other hand, when we run the C++ code, it takes approximately 0.000002 seconds (2 microseconds) to compute the factorial of 100. This means that C++ is approximately 12,500 times faster than Python for this example.

Conclusion

In this article, we compared the performance of C++ and Python using the example of computing the factorial of a large number. We found that C++ is significantly faster than Python for this example, with a performance improvement of approximately 12,500 times.

However, it is important to note that the performance of a programming language depends on the specific task being performed and the hardware being used. In general, C++ is a better choice for tasks that require high performance and efficiency, while Python is a better choice for tasks that require ease of use and flexibility.


Similar Articles