loop increment
- How to convert a for with a increment to Parallel.For?
for (int i = 0; i < n; i += block)
{
...
}
Answers
- The only way I know to do this is to make an enumerable, then use Parallel.ForEach:
IEnumerable<int> ForLoopBlock(int start, int end, int incr)
{
for (int i=start; i<end; i+=incr)
yield return i;
}
Then, you can do:
Parallel.ForEach (this.ForLoopBlock(0,n,block), (i) => { ... });
Reed Copsey, Jr. - http://reedcopsey.com- Marked As Answer byStephen Toub - MSFTMSFT, ModeratorThursday, October 01, 2009 4:47 PM
- Proposed As Answer byStephen Toub - MSFTMSFT, ModeratorMonday, September 28, 2009 11:47 PM
You could also do something like this:
public static void ParallelFor(
int fromInclusive, int toExclusive, int step, Action<int> body)
{
... // validate parameters here
if (step == 1){
Parallel.For(fromInclusive, toExclusive, body);
}
else // step > 1
{
int len = (int)Math.Ceiling(
(toExclusive - fromInclusive) / (double)step);
Parallel.For(0, len, i => body(fromInclusive + (i * step)));
}
}
- Marked As Answer byStephen Toub - MSFTMSFT, ModeratorThursday, October 01, 2009 4:47 PM
- Proposed As Answer byStephen Toub - MSFTMSFT, ModeratorMonday, September 28, 2009 11:47 PM
All Replies
- The only way I know to do this is to make an enumerable, then use Parallel.ForEach:
IEnumerable<int> ForLoopBlock(int start, int end, int incr)
{
for (int i=start; i<end; i+=incr)
yield return i;
}
Then, you can do:
Parallel.ForEach (this.ForLoopBlock(0,n,block), (i) => { ... });
Reed Copsey, Jr. - http://reedcopsey.com- Marked As Answer byStephen Toub - MSFTMSFT, ModeratorThursday, October 01, 2009 4:47 PM
- Proposed As Answer byStephen Toub - MSFTMSFT, ModeratorMonday, September 28, 2009 11:47 PM
You could also do something like this:
public static void ParallelFor(
int fromInclusive, int toExclusive, int step, Action<int> body)
{
... // validate parameters here
if (step == 1){
Parallel.For(fromInclusive, toExclusive, body);
}
else // step > 1
{
int len = (int)Math.Ceiling(
(toExclusive - fromInclusive) / (double)step);
Parallel.For(0, len, i => body(fromInclusive + (i * step)));
}
}
- Marked As Answer byStephen Toub - MSFTMSFT, ModeratorThursday, October 01, 2009 4:47 PM
- Proposed As Answer byStephen Toub - MSFTMSFT, ModeratorMonday, September 28, 2009 11:47 PM


