Created
March 29, 2022 11:48
-
-
Save hgomersall/1cd3bfc79a713a93f6e691cf24650cf1 to your computer and use it in GitHub Desktop.
A quick a dirty test on how long a tokio semaphore takes to add and acquire permits (as a pair)
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 tokio::sync::Semaphore; | |
use std::sync::Arc; | |
use std::time::Instant; | |
const LOOPS: usize = 1000000; | |
async fn twiddle(semaphore1: Arc<Semaphore>, semaphore2: Arc<Semaphore>) { | |
for _ in 0..LOOPS { | |
semaphore1.add_permits(1); | |
let permit = semaphore2.acquire().await.unwrap(); | |
permit.forget(); | |
} | |
} | |
#[tokio::main] | |
async fn main() { | |
let semaphore1 = Arc::new(Semaphore::new(0)); | |
let semaphore2 = Arc::new(Semaphore::new(0)); | |
let semaphore1_a = semaphore1.clone(); | |
let semaphore2_a = semaphore2.clone(); | |
let start_time = Instant::now(); | |
let handle1 = tokio::spawn( | |
async move { | |
twiddle(semaphore1, semaphore2).await; | |
} | |
); | |
let handle2 = tokio::spawn( | |
async move { | |
twiddle(semaphore2_a, semaphore1_a).await; | |
} | |
); | |
handle1.await.unwrap(); | |
handle2.await.unwrap(); | |
dbg!(start_time.elapsed()/(LOOPS as u32)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment