Skip to content

Instantly share code, notes, and snippets.

@tivrfoa
Last active November 20, 2023 21:53
Show Gist options
  • Save tivrfoa/548e3db3b8d58298f3b6e163f88b9f0a to your computer and use it in GitHub Desktop.
Save tivrfoa/548e3db3b8d58298f3b6e163f88b9f0a to your computer and use it in GitHub Desktop.
Rust tokio::spawn await
/*
$ cargo run --release --bin sp1
Finished release [optimized] target(s) in 0.09s
Running `target/release/sp1`
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
Seq dumb fibonacci took: 10.109140154s
--------------
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
Async dumb fibonacci took: 4.008534526s
*/
use std::time::Instant;
async fn async_dumb_fibonacci(n: u32) -> u32 {
dumb_fibonacci(n)
}
fn dumb_fibonacci(n: u32) -> u32 {
if n <= 1 {
return n;
}
dumb_fibonacci(n - 2) + dumb_fibonacci(n - 1)
}
const L: u32 = 35;
const R: u32 = 45;
#[tokio::main]
async fn main() {
let start = Instant::now();
for i in L..R {
println!("{}", dumb_fibonacci(i));
}
let duration = start.elapsed();
println!("Seq dumb fibonacci took: {:?}", duration);
println!("--------------");
// https://users.rust-lang.org/t/tokio-execute-async-for-loop-concurrently/43702/2
let start = Instant::now();
let mut handles = Vec::new();
for i in L..R {
let job = tokio::spawn(async_dumb_fibonacci(i));
handles.push(job);
}
for job in handles {
println!("{}", job.await.unwrap());
}
let duration = start.elapsed();
println!("Async dumb fibonacci took: {:?}", duration);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment