Simple Code to compare Speed of Python, Java, and C++?

Simple Code to compare Speed of Python, Java, and C++

Introduction

There’s often a lot of debate about the speed of different programming languages, with many assuming that C++ is always the fastest and Python is the slowest. However, it’s not as straightforward as it seems. In this article, I’ll walk you through simple programs with the same logic written in Python, Java, and C++ to provide a direct comparison of their speeds.

Speed of Python

import time

def sum_numbers(n):
    total = 0
    for i in range(1, n+1):
        total += i
    return total

n = 10**7  # Example large number
start_time = time.time()
result = sum_numbers(n)
end_time = time.time()

print(f"Result: {result}")
print(f"Execution time in Python: {end_time - start_time} seconds")

Output

0.3658 seconds

Spee of Java

public class Main {
    public static void main(String[] args) {
        long startTime = System.nanoTime();

        long n = 10000000;  // Example large number
        long sum = sumNumbers(n);

        long endTime = System.nanoTime();

        System.out.println("Result: " + sum);
        System.out.println("Execution time in Java: " + (endTime - startTime) / 1e9 + " seconds");
    }

    public static long sumNumbers(long n) {
        long total = 0;
        for (long i = 1; i <= n; i++) {
            total += i;
        }
        return total;
    }
}

Output

0.006528 seconds

Speed of C++

#include <iostream>
#include <chrono>

long long sumNumbers(long long n) {
    long long total = 0;
    for (long long i = 1; i <= n; i++) {
        total += i;
    }
    return total;
}

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

    long long n = 10000000;  // Example large number
    long long sum = sumNumbers(n);

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> duration = end - start;

    std::cout << "Result: " << sum << std::endl;
    std::cout << "Execution time in C++: " << duration.count() << " seconds" << std::endl;

    return 0;
}

Output

0.0080 seconds

Which is faster among Python, Java, and C++?

Mostly, people think C++ is the fastest, but here, Java is clearly the winner because it optimizes runtime performance through the use of the Just-In-Time (JIT) compiler, which dynamically compiles code during execution, resulting in faster execution times for long-running applications. Additionally, Java benefits from advanced garbage collection and memory management, reducing overhead in many scenarios compared to C++.

Conclusion

Speed is a different thing, but all three programming languages—Python, Java, and C++—have different use cases.

Python is mostly used for web development, scientific calculations, machine learning, data analytics, desktop GUI applications, and testing, among others. Python is an almost all-rounder. You can use Python for a wide range of tasks if speed is not a critical factor. One of Python’s biggest strengths is its rich ecosystem of libraries, which allows developers to quickly build applications without reinventing the wheel.

Java, on the other hand, is widely known for its portability and scalability. It is used extensively in enterprise-level applications, Android development, and large-scale systems. Its “write once, run anywhere” capability means Java is ideal for cross-platform applications. Java’s performance, while not as fast as C++, is generally faster than Python, making it suitable for applications where both portability and performance are important.

C++ is often considered the best choice when performance is critical. It is heavily used in areas such as system software, game development, real-time simulations, and applications requiring direct hardware interaction, like embedded systems. C++ gives programmers fine-grained control over system resources, and its speed is unmatched compared to Python and Java. If your task involves intensive computational work or real-time processing, C++ is usually the go-to language.

In conclusion, while Python excels in versatility and ease of use, Java strikes a balance between performance and portability, and C++ leads in raw speed and control, especially for performance-sensitive applications. The choice of language ultimately depends on the specific requirements of the project at hand.

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you