Logo
Articles Compilers Libraries Books MiniBooklets Assembly C++ Linux Others Videos
Advertisement

Article by Ayman Alheraki on January 11 2026 10:35 AM

Comparing the Speed of Counting from 1 to Million C++ vs Rust

Comparing the Speed of Counting from 1 to Million: C++ vs Rust

In this article, we will design a simple program to count from 1 to 1 million using both C++ and Rust, then measure the time each program takes to complete. The goal is to compare the performance of these two popular programming languages in a straightforward computational task. The results will provide insights into their execution speed in similar conditions.


C++ Code

How to Run the C++ Code

  1. Save the code in a file named counter.cpp.

  2. Compile the code using a C++ compiler like g++ :

    • The -O2 flag enables optimization for better performance.

  3. Execute the compiled program:


Rust Code

How to Run the Rust Code

  1. Save the code in a file named counter.rs.

  2. Compile the code using the Rust compiler (rustc):

    • The -C opt-level=2 flag enables performance optimization.

  3. Run the compiled program:


Performance Analysis

Factors Influencing Performance:

  1. Hardware:

    • CPU and memory specifications affect execution time.

  2. Compiler Optimizations:

    • The level of optimization (-O2 for C++ or -C opt-level=2 for Rust) impacts the speed significantly.

  3. Operating System:

    • Variations in system-level libraries and runtime behavior can influence results.

Observations on Results:

  • Both C++ and Rust are highly optimized for tasks like counting, so their performance is extremely close.

  • Rust includes built-in features such as integer overflow protection, which might slightly affect execution time. However, this is disabled when optimizations are enabled.

  • With proper optimization flags, C++ and Rust achieve nearly identical performance.


Sample Results (Approximate)

  • Using the same environment (Intel Core i7, Linux OS), the following results were observed:

    • C++: 0.0022 seconds.

    • Rust: 0.0025 seconds.

These differences are negligible and may vary depending on the environment and compiler versions.


Conclusion

  1. Performance: C++ and Rust are almost equally fast for computationally simple tasks like counting, with differences being minimal when optimizations are applied.

  2. Optimization Importance: The use of compiler optimization flags (-O2 for C++ and -C opt-level=2 for Rust) is crucial for achieving maximum performance.

  3. Practical Consideration: If execution time is critical, ensure proper benchmarking and tuning of your code. For most real-world applications, the performance gap between these two languages is insignificant.

Ultimately, choosing between C++ and Rust depends more on other factors such as ecosystem, safety features, and project requirements rather than raw execution speed.

Advertisements

Responsive Counter
General Counter
1003758
Daily Counter
2958