latency/
latency.rs

1use roblib_client::{transports::tcp::Tcp, Result, Robot};
2use std::{
3    env::args,
4    thread::sleep,
5    time::{Duration, Instant},
6};
7
8const NO_OF_RUNS: usize = 25;
9const WAIT_MS: u64 = 100;
10
11fn main() -> Result<()> {
12    // roblib_client::logger::init_log(Some("roblib_client=debug")); // uncomment if you want to spam the terminal
13
14    let ip = std::env::args()
15        .nth(1)
16        .unwrap_or_else(|| "localhost:1111".into());
17
18    let robot = Robot::new(Tcp::connect(ip)?);
19
20    // boring arg parsing
21    let mut args = args().skip(1);
22
23    let runs = args
24        .next()
25        .unwrap_or_else(|| NO_OF_RUNS.to_string())
26        .parse()
27        .unwrap_or(NO_OF_RUNS);
28
29    let wait_ms = args
30        .next()
31        .unwrap_or_else(|| WAIT_MS.to_string())
32        .parse()
33        .unwrap_or(WAIT_MS);
34
35    println!("Starting test with {runs} runs, in intervals of {wait_ms}ms",);
36
37    let start = Instant::now();
38    let mut v = Vec::with_capacity(runs);
39
40    for _ in 0..runs {
41        let r = robot.measure_latency()?.as_secs_f64();
42        v.push(r);
43        sleep(Duration::from_millis(wait_ms));
44    }
45
46    let sum = v.iter().sum::<f64>();
47    let min = v
48        .iter()
49        .copied()
50        .reduce(f64::min)
51        .expect("results contained NaN");
52    let max = v
53        .iter()
54        .copied()
55        .reduce(f64::max)
56        .expect("results contained NaN");
57
58    let avg = sum / v.len() as f64;
59    let dur = Instant::now().duration_since(start).as_millis() as f64 / 1000f64;
60
61    println!(
62        "Results:\n{v:?}\nRuns: {runs}\nTime elapsed: {dur}s\nMin: {min:.3}ms\nMax: {max:.3}ms\nAverage: {avg:.3}ms",
63        v=v.iter().map(|n|format!("{n:.3}").parse().unwrap()).collect::<Vec<f64>>()
64    );
65
66    Ok(())
67}