My main:
fn main() {
let time_1 = std::time::Instant::now();
test::test();
println!("Elapsed time_1: {:.3?}", time_1.elapsed());
}
and 2 async function:
async fn say_world() {
std::thread::sleep(std::time::Duration::from_secs(3));
println!("world");
}
async fn say_world_2() {
std::thread::sleep(std::time::Duration::from_secs(1));
println!("world_2");
}
Can someone explain / draw why i have different "elapsed time" ?
3 seconds mean that its work async
4 seconds mean that its work sync
And what is a difference between 2) and 3) ?
#[tokio::main]
pub async fn test() {
// Calling `say_world()` does not execute the body of `say_world()`.
let op_1 = tokio::task::spawn(say_world());
let op_2 = say_world_2();
// This println! comes first
println!("hello");
// Calling `.await` on `op` starts executing `say_world...`.
op_1.await;
op_2.await;
}
hello
world
world_2
Elapsed time_1: 4.002s
#[tokio::main]
pub async fn test() {
// Calling `say_world()` does not execute the body of `say_world()`.
let op_1 = say_world();
let op_2 = tokio::task::spawn(say_world_2());
// This println! comes first
println!("hello");
// Calling `.await` on `op` starts executing `say_world...`.
op_1.await;
op_2.await;
}
hello
world_2
world
Elapsed time_1: 3.002s
#[tokio::main]
pub async fn test() {
// Calling `say_world()` does not execute the body of `say_world()`.
let op_1 = tokio::task::spawn(say_world());
let op_2 = tokio::task::spawn(say_world_2());
// This println! comes first
println!("hello");
// Calling `.await` on `op` starts executing `say_world...`.
op_1.await;
op_2.await;
}
hello
world_2
world
Elapsed time_1: 3.003s