Created
October 6, 2023 11:06
-
-
Save Jensanf/982d072ea9a39985edbe6d51eeda88ea to your computer and use it in GitHub Desktop.
This code benchmarks the performance of crossbeam channels in Rust by sending a series of timestamped messages. It measures the message transmission time under two scenarios: with no delay and with a 100-microsecond delay between sending messages. The results, showing the average transmission duration, are printed to the console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use crossbeam::channel::{bounded, Receiver, Sender}; | |
use std::thread; | |
use std::time::{Duration, Instant}; | |
const MSG_COUNT: usize = 10_000; | |
const CAPACITY : usize = 100; | |
struct Message { | |
id: usize, | |
time_send: Instant, | |
} | |
fn main() { | |
println!("Crossbeam channel speed test"); | |
test_crossbeam_channel_speed(0); | |
println!("Crossbeam channel speed test with 100 microsecond delay"); | |
test_crossbeam_channel_speed(100); | |
} | |
fn test_crossbeam_channel_speed(delay: u64) { | |
let (tx, rx): (Sender<Message>, Receiver<Message>) = bounded(CAPACITY); | |
let mut execution_times: Vec<Duration> = Vec::new(); | |
let _send_thread = thread::spawn(move || { | |
for i in 0..MSG_COUNT { | |
thread::sleep(Duration::from_micros(delay)); | |
let mut message = Message { | |
id: i, | |
time_send: Instant::now(), | |
}; | |
message.time_send = Instant::now(); | |
tx.send(message).expect("Failed to send the message"); | |
} | |
}); | |
while let Ok(msg) = rx.recv() { | |
let elapsed = msg.time_send.elapsed(); | |
execution_times.push(elapsed); | |
} | |
let sum: Duration = execution_times.iter().sum(); | |
let mean: Duration = sum / (execution_times.len() as u32); | |
println!("Mean: {:?}", mean); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment