[Solved] Take n elems before passing to par_iter()

  1. I am using rayon::par_iter, and I have an x: Vec<T>

  2. Normally, I can do x.par_iter().map(...).collect() which processes all elements. However, I only want to process the first n elements (without truncating x itself to n elements).

  3. Question:Without truncating x itself to n elements, is there a way to par_iter over only the first n elements ?

It can run on a slice too;
x[0..n].par_iter()

2 Likes

Yes, a slice will do this. FWIW, I think x[..n] is more idiomatic, but there's no semantic difference.

You can also .take(n) on any IndexedParallelIterator. This might be preferable if you're not sure that your source actually has at least n elements, otherwise slicing will panic out of bounds.

1 Like

You mean x.par_iter().take(n) ?

If so, the 'laziness' of iters always confuses me, as intuitively, I imagine a 'fork' happening at the par_iter() step, and thus the take(n) makes no sense. However, given we're just "building up up a computation graph", and executing it later at collect(), then this makes sense.

iter should be renamed placeholder_to_do_stuff_later :slight_smile:

Yes, and you're right that laziness means nothing starts on the threadpool here yet.