Created
July 17, 2022 12:21
-
-
Save lordmauve/bb84b3ae5f3d8979ae477bf48f8898b1 to your computer and use it in GitHub Desktop.
High level vs low level languages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fib(): | |
a = 0 | |
b = 1 | |
while True: | |
yield a | |
a, b = b, a + b | |
for i, v in enumerate(fib(), start=1): | |
if i == 1_000_000: | |
break | |
print(v) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use num_bigint::BigUint; | |
struct Fib { | |
a: BigUint, | |
b: BigUint, | |
} | |
impl Fib { | |
fn new() -> Fib { | |
Fib { a: BigUint::from(0u64), b: BigUint::from(1u64) } | |
} | |
} | |
impl Iterator for Fib { | |
type Item = BigUint; | |
fn next(&mut self) -> Option<BigUint> { | |
let mut tmp: BigUint = &self.a + &self.b; | |
std::mem::swap(&mut self.a, &mut self.b); | |
std::mem::swap(&mut tmp, &mut self.b); | |
Some(tmp) | |
} | |
} | |
fn main() { | |
let millionth = Fib::new().skip(1_000_000 - 1).next().unwrap(); | |
println!("{}", millionth); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dev Time (s) | Run time (s) | RSS (MB) | ||
---|---|---|---|---|
Python | 100 | 11 | 10.5 | |
Rust | 707 | 6 | 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was a small experiment in comparing the productivity vs performance of Rust vs Python. This problem - finding the millionth Fibonacci number - was spitballed over drinks at a barbecue. It's not necessarily the most representative problem although I did allude to the fact that Python has built-in large integer support as being the kind of thing that is representative of it being a high level language.
The dev time comparison is pretty fair; I overcounted on the Python by getting my IDE set up, proper typing time was probably <60s. Meanwhile I had identified ahead of time that I would need the
num_bigint
crate in Rust, to compensate a bit for my lower level of familiarity with the Rust library ecosystem.I chose a similar iterator pattern in both languages. I think this is decently idiomatic in both. I considered doing something a bit tighter in Rust but I don't think I would actually do that when writing the code, and I can imagine that it might not be significantly faster.