Marcel Kopera
Marcel Kopera

Reputation: 314

Why same process takes longer in Rust than in Python?

I have a very simple code in python

x = "ABCD ss xx ta"
l = x.split(" ")

for i, y in enumerate(l):
    print(f"{i}: {y}")

which takes

real    0m0.037s
user    0m0.026s
sys     0m0.004s

I have done the same thing in Rust which is compiled - it should be faster

fn main() {
    let split = "ABCD ss xx ta".split(" ");
    for (i, s) in split.enumerate() {
        println!("{}:{}", i, s)
    }
}

which takes

real    0m0.159s
user    0m0.142s
sys     0m0.012s

I would like to ask here, why is compiled Python faster here than compiled Rust which I'm running with cargo run (already compiled)?

Upvotes: 0

Views: 154

Answers (1)

Scarfone
Scarfone

Reputation: 85

Firstly, i'm no python expert, but python as well as python3 does not run your code, i get errors. Changing it to:

x = "ABCD ss xx ta"
l = x.split(" ")

for i, y in enumerate(l):
    print(i , y)

Gives me (python 3):

real    0m0.020s
user    0m0.016s
sys 0m0.000s

Now for the real reason, I believe you are compiling with debug symbols as well as including the compliation time in your assertion. When I build your crate with cargo build --release and run the binary directly (which is put in ./target/release/), i get:

real    0m0.003s
user    0m0.000s
sys 0m0.000s

Which is far superior, (as rust normally is:))!

Upvotes: 2

Related Questions