numrs2 0.3.1

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Memory Optimization Performance Benchmarks
//!
//! Comprehensive benchmarks comparing memory-optimized operations against
//! standard implementations. Memory-optimized operations minimize allocations
//! through:
//! - Direct iteration (avoiding to_vec())
//! - In-place operations (reusing buffers)
//! - Buffer reuse patterns
//! - Stack allocation for small arrays

use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use numrs2::array::Array;
use std::hint::black_box;

/// Array sizes for testing
const SIZES: &[usize] = &[100, 1_000, 10_000, 100_000, 1_000_000];

/// Benchmark sum: sum_optimized vs sum
/// sum_optimized uses direct iteration without to_vec() allocation
fn bench_sum_comparison(c: &mut Criterion) {
    let mut group = c.benchmark_group("sum_comparison");

    for size in SIZES.iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| i as f64).collect();
        let array = Array::from_vec(data);

        // Standard sum (allocates via to_vec())
        group.bench_with_input(
            BenchmarkId::new("sum_standard", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.sum());
                    black_box(result);
                });
            },
        );

        // Optimized sum (no allocation, direct iteration)
        group.bench_with_input(
            BenchmarkId::new("sum_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.sum_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark product: product_optimized vs product
fn bench_product_comparison(c: &mut Criterion) {
    let mut group = c.benchmark_group("product_comparison");

    for size in SIZES.iter().take(4) {
        // Limit size to avoid overflow
        group.throughput(Throughput::Elements(*size as u64));

        // Use small values to avoid overflow
        let data: Vec<f64> = (0..*size).map(|i| 1.0 + (i as f64) * 0.0001).collect();
        let array = Array::from_vec(data);

        // Standard product (allocates via to_vec())
        group.bench_with_input(
            BenchmarkId::new("product_standard", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.product());
                    black_box(result);
                });
            },
        );

        // Optimized product (no allocation)
        group.bench_with_input(
            BenchmarkId::new("product_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.product_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark mean_optimized
/// Shows memory-efficient mean calculation with parallel support
fn bench_mean_optimized(c: &mut Criterion) {
    let mut group = c.benchmark_group("mean_optimized");

    for size in SIZES.iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| i as f64).collect();
        let array = Array::from_vec(data);

        group.bench_with_input(
            BenchmarkId::new("mean_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.mean_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark variance_optimized and std_optimized
fn bench_statistical_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("statistical_operations");

    for size in SIZES.iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| i as f64).collect();
        let array = Array::from_vec(data);

        group.bench_with_input(
            BenchmarkId::new("variance_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.variance_optimized());
                    black_box(result);
                });
            },
        );

        group.bench_with_input(
            BenchmarkId::new("std_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.std_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark in-place operations: map_inplace vs map
/// map_inplace modifies array in place, map allocates new array
fn bench_inplace_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("inplace_operations");

    for size in [1_000, 10_000, 100_000].iter() {
        group.throughput(Throughput::Elements(*size as u64));

        // Standard map (allocates new array)
        group.bench_with_input(
            BenchmarkId::new("map_allocating", size),
            size,
            |bencher, &size| {
                bencher.iter(|| {
                    let data: Vec<f64> = (0..size).map(|i| i as f64).collect();
                    let array = Array::from_vec(data);
                    let result = black_box(array.map(|x| x * 2.0 + 1.0));
                    black_box(result);
                });
            },
        );

        // In-place map (reuses existing array memory)
        group.bench_with_input(
            BenchmarkId::new("map_inplace", size),
            size,
            |bencher, &size| {
                bencher.iter(|| {
                    let data: Vec<f64> = (0..size).map(|i| i as f64).collect();
                    let mut array = Array::from_vec(data);
                    array.map_inplace(|x| x * 2.0 + 1.0);
                    black_box(&array);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark buffer reuse: map_to vs map
/// map_to writes to pre-allocated output buffer
fn bench_buffer_reuse(c: &mut Criterion) {
    let mut group = c.benchmark_group("buffer_reuse");

    for size in [1_000, 10_000, 100_000].iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| i as f64).collect();
        let array = Array::from_vec(data.clone());

        // Standard map (allocates new array each time)
        group.bench_with_input(
            BenchmarkId::new("map_allocating", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.map(|x| x.sqrt()));
                    black_box(result);
                });
            },
        );

        // map_to (reuses pre-allocated buffer)
        group.bench_with_input(
            BenchmarkId::new("map_to_reuse", size),
            size,
            |bencher, _| {
                let mut output = Array::from_vec(vec![0.0; *size]);
                bencher.iter(|| {
                    array
                        .map_to(|x| x.sqrt(), &mut output)
                        .expect("map_to should succeed");
                    black_box(&output);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark batch operations with buffer reuse
/// Shows cumulative benefit of avoiding allocations in loops
fn bench_batch_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("batch_operations");

    let size = 10_000;
    let iterations = 10;
    group.throughput(Throughput::Elements((size * iterations) as u64));

    let data: Vec<f64> = (0..size).map(|i| i as f64).collect();
    let array = Array::from_vec(data);

    // Without buffer reuse (allocates each iteration)
    group.bench_function("batch_without_reuse", |bencher| {
        bencher.iter(|| {
            for _ in 0..iterations {
                let result = array.map(|x| x.sqrt() + 1.0);
                black_box(result);
            }
        });
    });

    // With buffer reuse (single allocation)
    group.bench_function("batch_with_reuse", |bencher| {
        bencher.iter(|| {
            let mut output = Array::from_vec(vec![0.0; size]);
            for _ in 0..iterations {
                array
                    .map_to(|x| x.sqrt() + 1.0, &mut output)
                    .expect("map_to should succeed");
                black_box(&output);
            }
        });
    });

    group.finish();
}

/// Benchmark min/max operations
fn bench_minmax_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("minmax_operations");

    for size in SIZES.iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| (i as f64).sin()).collect();
        let array = Array::from_vec(data);

        group.bench_with_input(
            BenchmarkId::new("min_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.min_optimized());
                    black_box(result);
                });
            },
        );

        group.bench_with_input(
            BenchmarkId::new("max_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.max_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark axis operations
fn bench_axis_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("axis_operations");

    for size in [100, 500, 1000].iter() {
        let shape = vec![*size, *size];
        group.throughput(Throughput::Elements((size * size) as u64));

        let data: Vec<f64> = (0..(size * size)).map(|i| i as f64).collect();
        let array = Array::from_vec(data).reshape(&shape);

        // Sum along axis 0
        group.bench_with_input(
            BenchmarkId::new("sum_axis0_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(
                        array
                            .sum_axis_optimized(0)
                            .expect("sum_axis should succeed"),
                    );
                    black_box(result);
                });
            },
        );

        // Sum along axis 1
        group.bench_with_input(
            BenchmarkId::new("sum_axis1_optimized", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(
                        array
                            .sum_axis_optimized(1)
                            .expect("sum_axis should succeed"),
                    );
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

/// Benchmark allocation patterns - measure overhead of repeated operations
fn bench_allocation_overhead(c: &mut Criterion) {
    let mut group = c.benchmark_group("allocation_overhead");

    let size = 10_000;
    let data: Vec<f64> = (0..size).map(|i| i as f64).collect();
    let array = Array::from_vec(data);

    // Many small operations with allocation
    group.bench_function("many_allocations", |bencher| {
        bencher.iter(|| {
            for _ in 0..100 {
                let result = array.sum();
                black_box(result);
            }
        });
    });

    // Many small operations without allocation
    group.bench_function("no_allocations", |bencher| {
        bencher.iter(|| {
            for _ in 0..100 {
                let result = array.sum_optimized();
                black_box(result);
            }
        });
    });

    group.finish();
}

/// Benchmark SIMD acceleration in optimized operations
fn bench_simd_acceleration(c: &mut Criterion) {
    let mut group = c.benchmark_group("simd_acceleration");

    // Test with different sizes to show SIMD threshold (64 elements)
    for size in [32, 64, 128, 1024, 10_000].iter() {
        group.throughput(Throughput::Elements(*size as u64));

        let data: Vec<f64> = (0..*size).map(|i| i as f64).collect();
        let array = Array::from_vec(data);

        group.bench_with_input(
            BenchmarkId::new("sum_optimized_simd", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.sum_optimized());
                    black_box(result);
                });
            },
        );

        group.bench_with_input(
            BenchmarkId::new("variance_optimized_simd", size),
            size,
            |bencher, _| {
                bencher.iter(|| {
                    let result = black_box(array.variance_optimized());
                    black_box(result);
                });
            },
        );
    }

    group.finish();
}

criterion_group!(
    benches,
    bench_sum_comparison,
    bench_product_comparison,
    bench_mean_optimized,
    bench_statistical_operations,
    bench_inplace_operations,
    bench_buffer_reuse,
    bench_batch_operations,
    bench_minmax_operations,
    bench_axis_operations,
    bench_allocation_overhead,
    bench_simd_acceleration,
);
criterion_main!(benches);