Why does this Rust code takes twice the time to run compared to C++?
Hello,
I am very new to Rust (started just a few days).
I have created the following codes in Rust and C++:
// Rust code
fn main() {
let n:u128 = 1_000_000_000;
let mut s:u128 = 0;
for i in 1..=n {
if i == 125468716 {
s += 2*i;
}
s += i;
}
println!("Sum value: {s}");
}
and
// C++ code
#include <iostream>
int main() {
\tunsigned long long n = 1000000000;
\tunsigned long long s = 0;
\tfor (unsigned long long i = 1; i <= n; i++) {
if (i == 125468716) {
s += 2*i;
\t }
\t s += i;
\t}
\tstd::cout << "Sum: " << s << std::endl;
\treturn 0;
}
Using rustc 1.60.0 (7737e0b5c 2022-04-04), I have compiled the code as follows:
rustc -O main.rs -o rust_code
And for C++ code, I have used g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 , as follows:
g++ -O2 main.cpp -o cpp_code
When I run the two codes:
$ time ./rust_code
Sum value: 500000000750937432
real\t0m1.419s
user\t0m1.412s
sys\t0m0.009s
$ time ./cpp_code
Sum: 500000000750937432
real\t0m0.733s
user\t0m0.733s
sys\t0m0.000s
Why does the rust code take twice the time to run compared to C++ code?
Am I doing something wrong?
Thank you