Compare commits

..

1 Commits
sync ... main

Author SHA1 Message Date
df207f20fe Changed the code to run arynchronously 2023-05-22 14:14:52 +01:00
2 changed files with 33 additions and 15 deletions

View File

@ -6,6 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
futures = "0.3.28"
mongodb = "2.5.0"
serde = "1.0.163"
tokio = "1.28.1"

View File

@ -1,5 +1,8 @@
use mongodb::{Client, options::{ClientOptions, Credential}};
use std::time::{self, SystemTime};
use mongodb::{Client, options::{ClientOptions, Credential}, Collection};
use std::time::{self, SystemTime, Duration};
use tokio::task;
use std::sync::Mutex;
use std::sync::Arc;
mod packet;
use packet::Packet;
@ -28,26 +31,40 @@ async fn main() {
_ => {}
}
//Setup the number of queries that we want to run as well as Arcs and Mutexes to pass to threads
const NUM_QUERIES: u32 = 5_000;
let collection = db.collection::<Packet>("test");
let mut queries: Vec<std::time::Duration> = vec![];
let collection: Arc<Collection<Packet>> = Arc::new(db.collection::<Packet>("test"));
let mut tasks = vec![];
let queries: Arc<Mutex<Vec<Duration>>> = Arc::new(Mutex::new(vec![]));
let start_time = SystemTime::now();
//Start spawning threads to run the requests
for _ in 0..NUM_QUERIES {
tasks.push(task::spawn(run_query(collection.clone(), queries.clone())))
}
futures::future::join_all(tasks).await;
//Print out the results
for (i, duration) in queries.lock().unwrap().iter().enumerate() {
println!("{}: {}.{} milliseconds", i, duration.as_millis(), duration.as_micros());
}
println!("Ran {} queries in {}s", NUM_QUERIES, time::SystemTime::now().duration_since(start_time).unwrap().as_secs_f32());
}
/// Function that runs an upload to a a MongoDB collection with a recorded timestamp
/// asynchronously
async fn run_query(collection: Arc<Collection::<Packet>>, query_records: Arc<Mutex<Vec<Duration>>>) {
//Record the start time for a query
let query_time = SystemTime::now();
//Perform the insert
collection.insert_one(Packet{
time: SystemTime::now(),
text: format!("Current Unix time: {:?}", SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap())
}, None).await.unwrap();
//Record the duration and add it to the list
let duration = SystemTime::now().duration_since(query_time).unwrap();
queries.push(duration);
}
for (i, duration) in queries.iter().enumerate() {
println!("{}: {}.{} milliseconds", i, duration.as_millis(), duration.as_micros());
}
println!("Ran {} queries in {} seconds.", NUM_QUERIES, SystemTime::now().duration_since(start_time).unwrap().as_secs_f32());
query_records.lock().unwrap().push(duration);
}