There are nested loops, as a result, they call a function for calculating data, whose input parameters are 2 index parameters in loops. How can I maximize the parallelization of the passage through cycles? In fact, I have a complete search of two parameters.

 double optResult = 0; double result = 0; for (int i = 5; i < 50; i = i + 5) { for (int j = 5; j < 50; j = j + 5) { if (i < j) { optResult = OptimStart(i,j); if (optResult > result) { result = optResult; } } } } 

    2 answers 2

    I would do something like this

     void Main() { var tuples = new List<Tuple<int, int>>(); for (int i = 5; i < 50; i = i + 5) { for (int j = i+5; j < 50; j = j + 5) { tuples.Add(Tuple.Create(i, j)); } } var max = tuples.AsParallel().Max(t=>Foo(t.Item1, t.Item2)); Console.WriteLine(max); } int Foo(int i, int j) { Thread.Sleep(1000); return i+j; } 

    If there are too many combinations and you do not want to keep them in memory, then

     void Main() { var max = GetItems().AsParallel().Max(t=>Foo(t.Item1, t.Item2)); Console.WriteLine(max); } int Foo(int i, int j) { Thread.Sleep(1000); return i+j; } IEnumerable<Tuple<int, int>> GetItems() { for (int i = 5; i < 50; i = i + 5) { for (int j = i + 5; j < 50; j = j + 5) { yield return Tuple.Create(i, j); } } } 
    • Thank you very much. I will understand everything. Only in advance, all calculations in the OptimStart function in this example OptimStart where exactly? There will be a lot of calculations and half will need to be left in the cache later. - Fresto
    • In my example, I replaced the OptimStart function with Foo - that is, instead of calling my Foo you should call your function - tym32167
    • And, while I did not go into details, I thought that return i + j affects multithreading. Now everything is clear, thank you very much! - Fresto

    I would only suggest starting the nested loop not with 5 , but with i + 5 , and then the internal condition if (i < j) can be removed:

     double optResult = 0; double result = 0; for (int i = 5; i < 50; i = i + 5) { for (int j = i + 5; j < 50; j = j + 5) { optResult = OptimStart(i,j); if (optResult > result) { result = optResult; } } }