Rust: tokio,异步代码与运行速度初探

邮差的信 提交于 2021-01-04 14:10:41

几个问题:
1、同样的一段代码,放在异步中,运行速度会如何?
2、什么情况下异步并没有改变运行速度?
3、如何提升异步的速度?


toml:

[dependencies]
tokio = { version = "1", features = ["full"] }
futures = "0.3.4"

代码:

use std::time::{Duration, Instant};
use std::thread;
use tokio::time;
const N:i32 =1000000;
struct bar{
    price :f64,
    code: Option<String>,
    close: f64,
    open:f64,
    high:f64,
    low:f64,
}
impl bar{
    fn default()->Self{
        bar{
            price:0.0,
            code :Some(String::from("I AM NULL")),
            close:0.0,
            open:0.0,
            high:0.0,
            low:0.0,
        }
    }
    fn push_vec(n:i32)->Vec<Self>{
        let mut v = vec![];
        for _ in 0..N{
            v.push(bar::default());
        }
        v
    }
}



fn hello(){
    let v = bar::push_vec(N);
    println!("sync hello world ! v length :{:?}",v.len());
}

async fn async_hello(){
    let v = bar::push_vec(N);
    println!("async hello world ! v length :{:?}",v.len());
}
// 同步sleep
async fn sync_time_01() {
    std::thread::sleep(time::Duration::from_secs(1));//同步sleep
}
async fn sync_time_02() {
    std::thread::sleep(time::Duration::from_secs(1))//同步sleep
}
// 异步sleep
async fn async_time_01() {
    tokio::time::sleep(Duration::from_secs(1)).await;//异步sleep
}
async fn async_time_02() {
    tokio::time::sleep(Duration::from_secs(1)).await;//异步sleep
}
async fn sync_do() {
    async_hello().await;
    tokio::join!(sync_time_01(),sync_time_02());// 并行跑
    println!("sync_do is over!")
}

async fn async_do() {
    async_hello().await;
    tokio::join!(async_time_01(),async_time_02(),async_time_01(),async_time_02());//并行跑
    println!("async_do is over!")
}

#[tokio::main]
async fn main() {
    let start_0 = Instant::now();
    hello();
    println!("hello cost miliseconds[毫秒] : {}", start_0.elapsed().as_millis());

    let start_1 = Instant::now();
    async_hello().await;
    println!("async_hello cost miliseconds[毫秒] : {}", start_1.elapsed().as_millis());


    let start_2 = Instant::now();
    sync_do().await;
    println!("sync_do cost miliseconds[毫秒] : {}", start_2.elapsed().as_millis());
    let start_3 = Instant::now();
    async_do().await;
    println!("async_do cost miliseconds[毫秒] : {}", start_3.elapsed().as_millis());

}

ouput:


    Finished release [optimized] target(s) in 2.08s
     Running `target/release/test_trait`
sync hello world ! v length :1000000
hello cost miliseconds[毫秒] : 179
async hello world ! v length :1000000
async_hello cost miliseconds[毫秒] : 148
async hello world ! v length :1000000
sync_do is over!
sync_do cost miliseconds[毫秒] : 2137
async hello world ! v length :1000000
async_do is over!
async_do cost miliseconds[毫秒] : 1143

你能得出什么结论么?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!