[英]c# Parallel vs Sequential
我有一個很大的列表循環(1.500.000項),每個項目我都要做一個非常小的檢查。 完全在30秒內。
使用Sequential時的CPU利用率約為10%,因此沒有使用大量資源。
第一個想法是使用Parallel,但是由於每個項目的持續時間有限,Parallel比持續的Foreach持續時間更長,這是因為“ 為什么並行版本比這個例子中的順序版本慢? ”,這解釋了每項任務的創建都會花費時間。
所以我有另一個想法,那就是將列表分成4個(或更多)相等的和平並創建一個線程來遍歷項目以使其更快。
在創建自己的課程之前,這是一個好方法嗎? 或者關於如何加快速度的任何其他想法? 或者你知道更好的處理方法嗎?
我為另一個並行方法創建的代碼:(在我自己的靜態類中使用)
public static void ForEach<T>(IEnumerable<T> list, Action<T> body, int listDevide)
{
// Number of items
int items = list.Count();
// Divided (in int, so floored)
int listPart = items / listDevide;
// Get numbers extra for last run
int rest = items % listDevide;
// List to save the actions
var actions = new List<Action>();
for(var x = 0; x < listDevide; x++)
{
// Create the actions
actions.Add(delegate {
foreach(var item in list.Skip(x * listPart).Take(listPart))
{
body.Invoke(item);
}
});
}
// Run the actions parallel
Parallel.Invoke(actions.ToArray());
}
備注:此示例中當前未使用“rest”變量來執行最后一項。
解決方案如下,更多信息: http : //msdn.microsoft.com/en-us/library/dd997411.aspx
是的,對輸入數組進行分區是一種很好的方法。
實際上,Microsoft提供了一個Partitioner
類來幫助完成這種方法。
這是一個展示如何操作的示例:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
private void run()
{
double sum = 0;
Func<double, double> func = x => Math.Sqrt(Math.Sin(x));
object locker = new object();
double[] data = testData();
// For each double in data[] we are going to calculate Math.Sqrt(Math.Sin(x)) and
// add all the results together.
//
// To do this, we use class Partitioner to split the input array into just a few partitions,
// (the Partitioner will use knowledge about the number of processor cores to optimize this)
// and then add up all the values using a separate thread for each partition.
//
// We use threadLocalState to compute the total for each partition, and then we have to
// add all these together to get the final sum. We must lock the additon because it isn't
// threadsafe, and several threads could be doing it at the same time.
Parallel.ForEach
(
Partitioner.Create(0, data.Length),
() => 0.0,
(subRange, loopState, threadLocalState) =>
{
for (int i = subRange.Item1; i < subRange.Item2; i++)
{
threadLocalState += func(data[i]);
}
return threadLocalState;
},
finalThreadLocalState =>
{
lock (locker)
{
sum += finalThreadLocalState;
}
}
);
Console.WriteLine("Sum = " + sum);
}
private static double[] testData()
{
double[] array = new double[1000003]; // Test with an odd number of values.
Random rng = new Random(12345);
for (int i = 0; i < array.Length; ++i)
array[i] = rng.Next() & 3; // Don't want large values for this simple test.
return array;
}
static void Main()
{
new Program().run();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.