有人可以为我解释为什么PLinq在第一个示例中比正常的linq更好,但是在第二个示例中却最差?我看到唯一的区别是ExpensiveComputation()函数中的Thread.Sleep()
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace PlinqTest
{
public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public bool ExpensiveComputation()
{
Thread.Sleep(10);
return (Salary > 2000 && Salary < 3000);
}
public bool NonExpensiveComputation()
{
return (Salary > 2000 && Salary < 3000);
}
}
class Program
{
static void Main(string[] args)
{
List<Employee> employeeList = GetData();
Stopwatch stopWatch = new Stopwatch();
// Example 1
stopWatch.Start();
var linqResult = employeeList.Where<Employee>(e => e.ExpensiveComputation());
int empCount = linqResult.Count();
stopWatch.Stop();
Console.WriteLine(string.Format("Time taken by old LINQ in Expensive Computation is {0} to get {1} Employees", stopWatch.Elapsed.TotalMilliseconds, empCount));
stopWatch.Reset();
stopWatch.Start();
linqResult = employeeList.AsParallel<Employee>().Where<Employee>(e => e.ExpensiveComputation());
empCount = linqResult.Count();
stopWatch.Stop();
Console.WriteLine(string.Format("Time taken by new PLINQ in Expensive Computation is {0} to get {1} Employees", stopWatch.Elapsed.TotalMilliseconds, empCount));
stopWatch.Reset();
Console.WriteLine();
// Example 2
stopWatch.Start();
linqResult = employeeList.Where<Employee>(e => e.NonExpensiveComputation());
empCount = linqResult.Count();
stopWatch.Stop();
Console.WriteLine(string.Format("Time taken by old LINQ in Non Expensive Computation is {0} to get {1} Employees", stopWatch.Elapsed.TotalMilliseconds, empCount));
stopWatch.Reset();
stopWatch.Start();
linqResult = employeeList.AsParallel<Employee>().Where<Employee>(e => e.NonExpensiveComputation());
empCount = linqResult.Count();
stopWatch.Stop();
Console.WriteLine(string.Format("Time taken by new PLINQ in Non Expensive Computation is {0} to get {1} Employees", stopWatch.Elapsed.TotalMilliseconds, empCount));
stopWatch.Reset();
Console.ReadKey();
}
static List<Employee> GetData()
{
List<Employee> employeeList = new List<Employee>();
Random random = new Random(1000);
for (int i = 0; i < 500; i++)
{
employeeList.Add(new Employee() { Name = "Employee" + i, Salary = GetRandomNumber(random, 1000, 5000) });
}
return employeeList;
}
static double GetRandomNumber(Random random, double minimum, double maximum)
{
return random.NextDouble() * (maximum - minimum) + minimum;
}
}
}
这是结果:
旧的LINQ在昂贵的计算中花费的时间为 5458.0269 ,以吸引135名员工
新的PLINQ在昂贵的计算上花费的时间为 741.835 ,以获得135名员工
旧版LINQ在非昂贵计算中花费的时间为 0.3653 ,以获得135名员工
新PLINQ在非昂贵计算中花费的时间为 0.9175 ,以获取135名员工
答案 0 :(得分:1)
平行主义不是免费的,它有间接费用。如果您所做的工作量很小,那么间接费用可能会比您节省的时间更多。
我强烈建议您阅读免费的电子书Patterns of Parallel Programming,该书讨论了您遇到的问题,并很好地解释了这些问题。