Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make rand complex to multithread #7

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "stochastic-rs"
version = "0.7.0"
version = "0.7.1"
edition = "2021"
license = "MIT"
description = "A Rust library for stochastic processes"
Expand Down
10 changes: 10 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,14 @@ fn main() {
let sum: f32 = runs.iter().sum();
let average = sum / runs.len() as f32;
println!("Average time: {}", average);

let start = std::time::Instant::now();
let fbm = Fbm::new(0.75, 10000, Some(1.0), Some(1000));
let data = fbm.sample_par();
println!("Data: {:?}", data);
let duration = start.elapsed();
println!(
"Time elapsed in expensive_function() is: {:?}",
duration.as_secs_f32()
);
}
24 changes: 18 additions & 6 deletions src/noises/fgn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! The `FgnFft` struct provides methods to generate fractional Gaussian noise (FGN)
//! using the Fast Fourier Transform (FFT) approach.

use std::sync::Arc;
use std::sync::{Arc, Mutex};

use crate::utils::Generator;
use ndarray::parallel::prelude::*;
Expand Down Expand Up @@ -101,11 +101,23 @@ impl Generator for FgnFft {
/// let sample = fgn_fft.sample();
/// ```
fn sample(&self) -> Array1<f64> {
let rnd = Array1::<Complex<f64>>::random(
2 * self.n,
ComplexDistribution::new(StandardNormal, StandardNormal),
);
let fgn = &*self.sqrt_eigenvalues * &rnd;
let num_threads = rayon::current_num_threads();
let chunk_size = (2 * self.n) / num_threads;
let rnd = Arc::new(Mutex::new(Array1::<Complex<f64>>::zeros(2 * self.n)));

(0..num_threads).into_par_iter().for_each(|i| {
let chunk = Array1::<Complex<f64>>::random(
chunk_size,
ComplexDistribution::new(StandardNormal, StandardNormal),
);

let mut result_lock = rnd.lock().unwrap();
result_lock
.slice_mut(s![i * chunk_size..(i + 1) * chunk_size])
.assign(&chunk);
});

let fgn = &*self.sqrt_eigenvalues * &*rnd.lock().unwrap();
let mut fgn_fft = Array1::<Complex<f64>>::zeros(2 * self.n);
ndfft(&fgn, &mut fgn_fft, &*self.fft_handler, 0);
let scale = (self.n as f64).powf(-self.hurst) * self.t.powf(self.hurst);
Expand Down
Loading