Here's a simple n-th prime program written in Rust. The implementation is inefficient, but that's not the point.
use std::time::Instant;
fn main() {
let n = 10_000;
let now = Instant::now();
let nth = nth_prime(n);
let elapsed = now.elapsed().as_micros();
println!("prime #{} = {}", n, nth);
println!("elapsed = {} µs", elapsed);
}
fn nth_prime(n: u64) -> u64 {
let mut count = 1;
let mut num = 2;
while count < n {
num += 1;
if is_prime(num) {
count += 1;
}
}
num
}
fn is_prime(num: u64) -> bool {
for i in 2..num {
if num % i == 0 {
return false;
}
}
true
}
If I run this program on macOS natively with cargo run --release
, I get a consistent execution time of ~3.4 seconds. However, if I run this program with Docker Desktop (on the same laptop), I get a consistent execution time of ~1.7 seconds. Here's the Dockerfile I'm using:
FROM rust:1.50
WORKDIR /usr/src/playground
COPY Cargo.toml .
COPY Cargo.lock .
COPY src src
RUN cargo build --release
CMD cargo run --release
However, if I switch all the u64
s for u32
s, then the native executable runs consistently in ~1.5 seconds, while the Docker version runs consistently in ~1.6 seconds.
Is the Linux executable optimized in a way that the macOS executable isn't?
Note that I get the same behaviour on macOS Big Sur Version 11.2.2 and on macOS Catalina Version 10.15.17. I'm using Docker Desktop Version 3.1.0 with Engine Version 20.10.2 on both laptops, and I'm using Cargo Version 1.50.0 on both laptops.
Also, note that I tried the same benchmark on an Ubuntu 18.04 Desktop. Both the native Linux executable (cargo run --release
) and the Docker version (docker run
) run consistently in ~1.02 seconds for the u64
program.
Thanks!