multithreaded.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //! randomx example that calculates many hashes using multiple threads
  2. use randomx::*;
  3. use std::sync::Arc;
  4. use std::thread;
  5. use std::time::Instant;
  6. use std::vec::Vec;
  7. fn main() {
  8. const NUM_THREADS: u32 = 8;
  9. // number of hashes to perform in each thread, not the total.
  10. const NUM_HASHES: u32 = 5000;
  11. let start = Instant::now();
  12. // Try adding `| RandomXFlags::LARGEPAGES`.
  13. let flags = RandomXFlags::default() | RandomXFlags::FULLMEM;
  14. let dataset = Arc::new(RandomXDataset::new(flags, b"key", NUM_THREADS as usize).unwrap());
  15. println!("Dataset initialised in {}ms", start.elapsed().as_millis());
  16. let mut handles = Vec::new();
  17. let start = Instant::now();
  18. for i in 0..NUM_THREADS {
  19. let dataset = dataset.clone();
  20. handles.push(thread::spawn(move || {
  21. let mut nonce: u32 = i;
  22. let vm = RandomXVM::new_fast(flags, &dataset).unwrap();
  23. for _ in 0..NUM_HASHES {
  24. let _ = vm.hash(&nonce.to_be_bytes());
  25. // e.g. thread 0 will use nonces 0, 8, 16, ...
  26. // and thread 1 will use nonces 1, 9, 17, ...
  27. nonce += NUM_THREADS;
  28. }
  29. }));
  30. }
  31. for handle in handles {
  32. let _ = handle.join();
  33. }
  34. println!(
  35. "Completed {} hashes in {}ms",
  36. NUM_THREADS * NUM_HASHES,
  37. start.elapsed().as_millis()
  38. );
  39. }