估计并行任务 运行 的时间量

Estimating Amount Of time For Tasks Running in Parallel

我有一个项目列表,根据一些计算每个项目需要一定的时间,要花费的时间是项目特定的。 括号中的数字是当 executed.Time 以秒为单位

时每个项目将花费的时间

例如。我有 5 件物品 - 物品 1 (2)、物品 2(1)、物品 3(4)、物品 4(3)、物品 5(2)。

我准备了一个由项目组成的列表,假设该列表称为 List1 并且包含项目 - Item1、Item3、Item5。

现在这些项目基本上代表了某些操作,(请假设没有像 I/O、处理器等外部因素影响这些项目/步骤)

foreach(var x in List1)
{
   // How to execute the items actually in Parallel 
}

问题1:如何真正保证这些项目运行并行。使用TLP(任务并行库)是一个选项,如果是如何使用它。

问题 2:现在在这种情况下,当它们实际上 运行 并行时,可以安全地说所花费的时间量将是列表中项目的最大时间量。在这种情况下,4 秒,因为 Item3 在 List1 的所有项目中最高。

Question1: How to actually ensure that these items run in parallel. Is using TLP (task parallel library) an option, if yes how to use it.

使用 TPL 将是最佳选择,但您的进程是 IO 绑定还是 CPU 绑定确实很重要。简单来说,如果该过程纯粹是一个 CPU 耗时的操作,那么您将受到 CPU 的约束,否则,如果您正在执行 IO,那么您的 IO 就会受到约束。以下是每个示例:

public class IO_Item
{
    public Task Process() => Task.CompletedTask;
}

public Task ProcessAll_IOBound(IList<IO_Item> items)
{
    var tasks = items.Select(item => item.Process());
    return Task.WhenAll(tasks);
}

public class CPU_Item
{
    public void Process() { }
}

public void ProcessAll_CPUBound(IList<CPU_Item> items)
{
    Parallel.ForEach(items, item => item.Process());
}

Question2: Now in this case when they actually run in parallel , is it safe to say that the amount of time taken will be maximum of amount of time of the Item in the list. In this case 4 seconds as Item3 is having highest among all the items of List1.

不一定。首先 运行ning 并行并不一定意味着所有项目都同时进行。他们可能会被分批处理、阻塞或以其他方式不得不等待轮到 运行,从而增加总时间。另外,请记住并行操作并非没有开销。就性能而言,最好分析一个真实的测试用例,看看数字告诉你什么。