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

#1
  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 ?

0 Likes

#2

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

2 Likes

#3

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

#4

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.

0 Likes

#5

iter should be renamed placeholder_to_do_stuff_later :slight_smile:

0 Likes

#6

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

0 Likes