Skip to main content

sequential_try_recv/
sequential-try_recv.rs

1//! `send/try_recv` 10,000,000 messages in sequence:
2//!
3//! ~25ns per send, ~35ns per `try_recv`
4
5use std;
6use unbounded_spsc;
7
8const MESSAGE_COUNT : u64 = 10_000_000;
9
10#[derive(Debug,PartialEq)]
11struct Mystruct {
12  x : f64,
13  y : f64,
14  z : f64
15}
16
17fn sendfun (sender : unbounded_spsc::Sender <Mystruct>) {
18  let mut counter = 0;
19  let start_time = std::time::SystemTime::now();
20  while counter < MESSAGE_COUNT {
21    sender.send (Mystruct { x: counter as f64, y: 1.5, z: 2.0 }).unwrap();
22    counter += 1;
23  }
24  let duration = start_time.elapsed().unwrap();
25  let duration_ns
26    = (duration.as_secs() * 1_000_000_000) + duration.subsec_nanos() as u64;
27  println!("sendfun duration ns: {duration_ns}");
28  println!("sendfun ns per message: {}", duration_ns / MESSAGE_COUNT);
29}
30
31fn recvfun (receiver : unbounded_spsc::Receiver <Mystruct>) {
32  let start_time = std::time::SystemTime::now();
33  loop {
34    match receiver.try_recv() {
35      Ok  (_m) => (),
36      Err (unbounded_spsc::TryRecvError::Empty) => (),
37      Err (unbounded_spsc::TryRecvError::Disconnected) => break
38    }
39  }
40  let duration = start_time.elapsed().unwrap();
41  let duration_ns
42    = (duration.as_secs() * 1_000_000_000) + duration.subsec_nanos() as u64;
43  println!("recvfun duration ns: {duration_ns}");
44  println!("recvfun ns per message: {}", duration_ns / MESSAGE_COUNT);
45  println!("buffer ending capacity: {}", receiver.capacity());
46}
47
48fn main() {
49  println!("main...");
50  let (sender, receiver) = unbounded_spsc::channel();
51  let join_sender = std::thread::spawn (move || sendfun (sender));
52  join_sender.join().unwrap();
53  let join_receiver = std::thread::spawn (move || recvfun (receiver));
54  join_receiver.join().unwrap();
55  println!("...main");
56}