使用C#中的任务并行库的并行操作的时序 [英] Timing of parallel actions using the Task Parallel Library in C#

查看:590
本文介绍了使用C#中的任务并行库的并行操作的时序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一些实验,计时和比较时间,找到最好的算法。出现的问题是如果并行运行任务会使实验的相对运行时间错误,并且如果我通过顺序运行它们来获得更具代表性的结果。下面是一个(简化版)代码:

I am running some experiments, timing them and comparing the times to find the best "algorithm". The question that came up was if running the tasks in parallel would make the relative runningtimes of the experiments wrong and if I would get more representative results by running them sequentially. Here is a (simplified) version of the code:

public static void RunExperient(IEnumerable<Action> experiments)
    {
        Parallel.ForEach(experiments, experiment =>
        {
            var sw = Stopwatch.StartNew(); //line 1
            experiment();                  //line 2   
            sw.Stop();                     //line 3
            Console.WriteLine(@"Time was {0}", sw.ElapsedMilliseconds);
        });
    }

我的问题是关于幕后发生的事情:

My questions are about what is happening "behind the scenes":


  1. 当任务开始时,操作系统或框架可能在其执行期间暂停任务,实验的运行时间错误?

  1. When a task has started, is it possible that the OS or the framework can suspend the task during its execution and continue on later making the running time of the experiment all wrong?

我会按顺序运行实验来获得更具代表性的结果吗?

Would I get more representative results by running the experiments sequentially?


推荐答案

这取决于你运行的机器和实验做什么,但一般答案是肯定的,他们可能相互影响。主要是通过资源匮乏。例如:

That depends on the machine that you are running on and what the experiments do, but generally the answer is yes, they may affect one another. Mainly through resource starvation. Here's an example:

public class Piggy { 
   public void GreedyExperiment() { 
       Thread.Priority = ThreadPriority.Highest;
       for (var i=0;i<1000000000;i++) {
           var j = Math.Sqrt(i / 5);
       }
   }
}

循环在高优先级线程,这将基本上消耗一个处理器,直到它完成。如果机器中只有一个处理器,TPL决定在其上安排两个实验,另一个将被饿死CPU时间。

That's going to do a tight loop on a high priority thread, which will basically consume one processor until it is done. If you only have one processor in the machine and TPL decides to schedule two experiments on it, the other one is going to be starved for CPU time.

这篇关于使用C#中的任务并行库的并行操作的时序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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