Rust: tokio,異步代碼與運行速度初探

幾個問題:
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

你能得出什麼結論麼?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章