Created
April 3, 2020 07:59
-
-
Save junha1/1d9c576b034f39f4767ce2bc3661e01e to your computer and use it in GitHub Desktop.
Simple example of Rust's asynchronous and concurrent executions
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 rand::Rng; | |
use std::thread; | |
use std::time; | |
use std::time::Instant; | |
use tokio::time::delay_for; | |
const MAX: usize = 1000; | |
async fn do_something(x: usize) -> usize { | |
let mut rng = rand::thread_rng(); | |
delay_for(time::Duration::from_millis(rng.gen_range(1, 10))).await; | |
x | |
} | |
fn do_something_but_no_async(x: usize) -> usize { | |
let mut rng = rand::thread_rng(); | |
thread::sleep(time::Duration::from_millis(rng.gen_range(1, 10))); | |
x | |
} | |
fn consume_all_sequentially() { | |
let mut result = vec![0; MAX]; | |
for i in 0..MAX { | |
result[i] = do_something_but_no_async(i); | |
} | |
//println!("{}", result.iter().sum::<usize>()); | |
} | |
fn consume_all_with_threads() { | |
let mut threads = Vec::new(); | |
for i in 0..MAX { | |
threads.push(Some(thread::spawn(move || do_something_but_no_async(i)))); | |
} | |
let mut result = vec![0; MAX]; | |
for i in 0..MAX { | |
result[i] = threads[i].take().unwrap().join().unwrap(); | |
} | |
//println!("{}", result.iter().sum::<usize>()); | |
} | |
fn consume_all_but_join_sequentially() { | |
let mut rt = tokio::runtime::Runtime::new().unwrap(); | |
let mut tasks = Vec::new(); | |
for i in 0..MAX { | |
tasks.push(do_something(i)); | |
} | |
let mut result = vec![0; MAX]; | |
for i in 0..MAX { | |
result[i] = rt.block_on(tasks.pop().unwrap()); | |
} | |
//println!("{}", result.iter().sum::<usize>()); | |
} | |
fn consume_all_and_join_together() { | |
let mut rt = tokio::runtime::Runtime::new().unwrap(); | |
let mut tasks = Vec::new(); | |
for i in 0..MAX { | |
tasks.push(do_something(i)); | |
} | |
let result = rt.block_on(futures::future::join_all(tasks)); | |
//println!("{}", result.iter().sum::<usize>()); | |
} | |
pub fn test_all() { | |
{ | |
let now = Instant::now(); | |
consume_all_sequentially(); | |
println!("{}", now.elapsed().as_millis()); | |
} | |
{ | |
let now = Instant::now(); | |
consume_all_with_threads(); | |
println!("{}", now.elapsed().as_millis()); | |
} | |
{ | |
let now = Instant::now(); | |
consume_all_but_join_sequentially(); | |
println!("{}", now.elapsed().as_millis()); | |
} | |
{ | |
let now = Instant::now(); | |
consume_all_and_join_together(); | |
println!("{}", now.elapsed().as_millis()); | |
} | |
/* | |
RESULT: | |
5056 | |
226 | |
6036 | |
31 | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment