Feature-Based Parallelism
The parallel module behavior is controlled by theserial feature flag:
serial is NOT enabled:
- Uses Rayon for parallel execution
- Automatically utilizes multiple CPU cores
- Best for production and performance-critical code
serial IS enabled:
- Falls back to standard sequential iterators
- Single-threaded execution
- Best for testing, debugging, and WebAssembly
Core Macros
cfg_iter!
Creates a parallel or serial iterator over references.
cfg_iter! with Minimum Length
Control the minimum chunk size for parallel execution:
cfg_iter_mut!
Creates a parallel or serial iterator over mutable references.
cfg_into_iter!
Creates a parallel or serial consuming iterator.
cfg_chunks!
Iterates over fixed-size chunks.
cfg_chunks_mut!
Iterates over mutable fixed-size chunks.
Collection Macros
cfg_keys!
Iterates over keys in a map.
cfg_values!
Iterates over values in a map.
Reduction Macros
cfg_reduce!
Applies a reduction operation.
cfg_reduce_with!
Reduces with a binary operation (no identity needed).
Option because the collection might be empty.
Search Macros
cfg_find!
Finds an element matching a predicate.
cfg_find_map!
Finds and transforms an element.
Sorting Macros
cfg_sort_unstable_by!
Sorts a slice using an unstable sort.
cfg_sort_by_cached_key!
Sorts using a cached key function.
ExecutionPool
For dynamic job scheduling, useExecutionPool:
With Capacity
Pre-allocate for better performance:CPU Detection
The module detects CPU type to optimize thread usage.max_available_threads()
Returns the optimal number of threads for the current CPU.
- Returns physical core count
- Avoids hyperthreading overhead
- Better for CPU-intensive cryptographic operations
- Returns all available threads
- Leverages simultaneous multithreading (SMT)
- Better overall throughput
- Returns all available threads
- Safe default
execute_with_max_available_threads()
Executes a closure with optimal thread count.
Common Patterns
Parallel Map
Parallel Filter
Parallel Filter-Map
Parallel Sum
Parallel Validation
Parallel Try-Map
Performance Guidelines
When to Use Parallelism
Good candidates for parallelization:- Large datasets (>1000 items)
- CPU-intensive operations per item
- Independent computations (no shared state)
- Cryptographic operations (hashing, signatures, proofs)
- Small datasets (<100 items)
- I/O-bound operations
- Operations with heavy synchronization
- Very fast operations (overhead dominates)
Example: Choosing Serial vs Parallel
Minimum Length Tuning
Use minimum length to avoid over-parallelization:Testing with Serial Mode
For deterministic tests, enable serial mode:- Deterministic execution order
- Easier debugging
- No race conditions in tests
WebAssembly Support
For WebAssembly targets, always use serial mode:Example: Parallel Proof Verification
Example: Parallel Batch Processing
Example: Dynamic Job Scheduling
Next Steps
- Utilities Overview - Overview of all utility modules
- Serialization - Canonical serialization traits