Ask a questionAsk a question
 

Answerloop increment

  • Monday, September 28, 2009 8:19 PMykwok Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    How to convert a for with a increment to Parallel.For?

    for (int i = 0; i < n; i += block)
    {
    ...
    }

Answers

  • Monday, September 28, 2009 8:26 PMReed Copsey, Jr. Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    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
  • Monday, September 28, 2009 11:46 PMStephen Toub - MSFTMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    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)));

        }

    }

     

All Replies

  • Monday, September 28, 2009 8:26 PMReed Copsey, Jr. Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    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
  • Monday, September 28, 2009 11:46 PMStephen Toub - MSFTMSFT, ModeratorUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    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)));

        }

    }