将parallell循环结果保存到列表中 [英] Saving parallell loop results to a list

查看:91
本文介绍了将parallell循环结果保存到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何保存并行循环中调用的方法的结果,该方法将双重结果返回到列表?每次运行该方法时,它都会返回一个结果。我想将该特定结果添加到列表中。



秒表sw =新秒表(); 
sw.Start();
for(int i = 0; i< 10; i ++)
{
SumRootN(i,t);
}
sw.Stop();

秒表sw2 =新秒表();
sw2.Start();


//需要保存结果列表
Parallel.For(0,10,i => SumRootN(i,t));


sw2.Stop();
double t = sw2.ElapsedTicks;
Console.WriteLine(Seq+ sw.ElapsedMilliseconds);
Console.WriteLine(Parallel+ sw2.ElapsedMilliseconds);





  public   static   double  SumRootN( int  root,< span class =code-keyword> string  test)
{

double result = 0 ;
for int i = 1 ; i < 1000000 ; i ++)
{
result + = Math.Exp(Math.Log(i)/ root);

}
返回结果;
}

解决方案

我不完全确定这是否正是你需要的,但并行聚合 [ ^ ]可能是您的解决方案。


shekarchee已关闭,但如果您需要保留结果如果它不是并行执行的相同序列,那么最简单的是使用数组而不是 List< double>

< pre lang =c#> const int count = 10 ;
double [] results = new double < /跨度> [数];
Parallel.For( 0 ,count,i = > {results [i] = SumRootN(i, t);});


How do I save the results of the method called in the parallel loop that returns a double result to a list? Each time the method is run it returns a result. I want to add that specific result to a list.

Stopwatch sw = new Stopwatch();
     sw.Start();
     for (int i = 0; i < 10; i++)
     {
         SumRootN(i,"t");
     }
     sw.Stop();

     Stopwatch sw2 = new Stopwatch();
     sw2.Start();


     //NEED TO SAVE RESULTS TO LIST
     Parallel.For(0, 10, i => SumRootN(i,"t"));


     sw2.Stop();
     double t = sw2.ElapsedTicks;
     Console.WriteLine("Seq " + sw.ElapsedMilliseconds);
     Console.WriteLine("Parallel " + sw2.ElapsedMilliseconds);



public static double SumRootN(int root,string test)
       {

           double result = 0;
           for (int i = 1; i < 1000000; i++)
           {
               result += Math.Exp(Math.Log(i) / root);

           }
           return result;
       }

解决方案

I''m not entirely sure if this is exactly what you need, but Parallel Aggregation[^] might be your solution.


shekarchee is close, but if you need to keep the results in the same sequence as if it was NOT performed in parallel, then the simplest is to use an array instead of the List<double>.

const int count = 10;
double[] results = new double[count];
Parallel.For(0, count, i => { results[i] = SumRootN(i, "t"); });


这篇关于将parallell循环结果保存到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆