大红包 请教一个 rust 延迟的问题,

2022-01-20 19:09:36 +08:00
 EricJia
  1. 在片段一中执行 解析 json 只需要 2us , 为何在 片段二中,加了行 sleep 代码后执行时间慢到 60us ?
  2. 为何 websocket 库中 read message loop 中解析 json 也是慢到 20-60us?

rust 中 sleep 代码实现

#[cfg(not(target_os = "espidf"))]
    pub fn sleep(dur: Duration) {
        let mut secs = dur.as_secs();
        let mut nsecs = dur.subsec_nanos() as _;

        // If we're awoken with a signal then the return value will be -1 and
        // nanosleep will fill in `ts` with the remaining time.
        unsafe {
            while secs > 0 || nsecs > 0 {
                let mut ts = libc::timespec {
                    tv_sec: cmp::min(libc::time_t::MAX as u64, secs) as libc::time_t,
                    tv_nsec: nsecs,
                };
                secs -= ts.tv_sec as u64;
                let ts_ptr = &mut ts as *mut _;
                if libc::nanosleep(ts_ptr, ts_ptr) == -1 {
                    assert_eq!(os::errno(), libc::EINTR);
                    secs += ts.tv_sec as u64;
                    nsecs = ts.tv_nsec;
                } else {
                    nsecs = 0;
                }
            }
        }
    }
use serde::{Serialize, Deserialize};
use std::time::Instant;
use std::time;

use tungstenite::{connect,  Message};
use url::Url;

#[derive(Serialize, Deserialize)]
pub struct OkexWsArg {
    pub channel: String,
    #[serde(rename(deserialize = "instId"))]
    pub inst_id: String,
}
#[derive(Serialize, Deserialize)]
pub struct  OkexWsDepthItem {
    pub asks: [[String; 4]; 5],
    pub bids: [[String; 4]; 5],
    #[serde(rename(deserialize = "instId"))]
    pub inst_id: String,
    pub ts: String,
}
#[derive(Serialize, Deserialize)]
pub struct OkexWsDepth {
    pub arg: OkexWsArg,
    pub data: [OkexWsDepthItem; 1],
}

fn main(){
    // 片段一
    for n in 0..10 {
        let start = Instant::now();
        let raw_msg = r#"{"arg":{"channel":"books5","instId":"BTC-USDT-SWAP"},"data":[{"asks":[["42185.1","959","0","32"],["42186.4","132","0","2"],["42186.7","6","0","6"],["42186.9","59","0","2"],["42187.2","19","0","2"]],"bids":[["42185","285","0","6"],["42183.3","15","0","1"],["42181.8","3","0","1"],["42181.7","6","0","3"],["42181.6","46","0","18"]],"instId":"BTC-USDT-SWAP","ts":"1642613619147"}]}"#;
        match  serde_json::from_str::<OkexWsDepth>(&raw_msg.to_string()) {
            Ok(msg) => {
                println!("parse: {}", msg.data.first().unwrap().ts);
            },
            Err(err) => {
                println!("parse error {:?} {:?}", raw_msg, err);
            }
        }
        println!("1-{} time cost: {:?} us",n, start.elapsed().as_micros());
    }
    // 片段二
    for n in 0..10 {
        std::thread::sleep(time::Duration::from_millis(100));
        let start = Instant::now();
        let raw_msg = r#"{"arg":{"channel":"books5","instId":"BTC-USDT-SWAP"},"data":[{"asks":[["42185.1","959","0","32"],["42186.4","132","0","2"],["42186.7","6","0","6"],["42186.9","59","0","2"],["42187.2","19","0","2"]],"bids":[["42185","285","0","6"],["42183.3","15","0","1"],["42181.8","3","0","1"],["42181.7","6","0","3"],["42181.6","46","0","18"]],"instId":"BTC-USDT-SWAP","ts":"1642613619147"}]}"#;
        match  serde_json::from_str::<OkexWsDepth>(&raw_msg.to_string()) {
            Ok(msg) => {
                println!("parse: {}", msg.data.first().unwrap().ts);
            },
            Err(err) => {
                println!("parse error {:?} {:?}", raw_msg, err);
            }
        }
        println!("2-{} time cost: {:?} us",n, start.elapsed().as_micros());
    }
}

956 次点击
所在节点    问与答
2 条回复
OSDI
2022-01-20 19:20:10 +08:00
sleep 进程挂起调度开销不小
EricJia
2022-01-20 19:32:43 +08:00
@OSDI #1 感谢您的回答,请问在 websocket 库中 `tokio-tungstenite` `tungstenite` 等等 read message 循环中解析 json 延迟也很高, 也是因为类似原因吗?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/829542

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX