首页 > 解决方案 > 如何测量并行处理中运行的每个任务的时间?

问题描述

我有一组项目并根据批量大小(例如 1000 个项目)拆分项目,并将项目传递给并行处理。我们如何知道正在产生哪个线程并测量每个批处理集的性能日志并行运行的时间?

下面是示例代码。

public static class Program
{
    static void Main(string[] args)
    {
        var chunks = Enumerable.Range(1, 10000).Batch(1000);

        for each (var item in chunks)
        {
            RunParallel(item);
        }

        Console.ReadKey();
    }

    public static List<int> RunParallel(IEnumerable<int> chunkItems)
    {
        ConcurrentBag<int> bag = new ConcurrentBag<int>();
        Parallel.ForEach(chunkItems, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (item) =>
        {
            //Consider this as db processing. 
            bag.Add(item); 
        });

        return bag.ToList();
    }

    public static IEnumerable<IEnumerable<TSource>> Batch<TSource>(this IEnumerable<TSource> source, long batchSize)
    {
        var items = new TSource[batchSize];
        var count = 0;
        foreach (var item in source)
        {
            items[count++] = item;
            if (count == batchSize)
            {
                yield return items;
                items = new TSource[batchSize];
                count = 0;
            }
        }
        if (count > 0)
            yield return items.Take(count);
    }
}

标签: c#parallel-processingparallel.foreach

解决方案


您可以使用传递当前迭代索引的 Parallel.ForEach 的 另一个重载:Parallel.ForEach(list, (item,state,index) => {YourFunction(index);} );

您可以在要测量其执行时间的函数中使用秒表。

 Stopwatch stopWatch = new Stopwatch();
 stopWatch.Start();
 //your logic goes here
 stopWatch.Stop();
 //Get the elapsed time as a TimeSpan value.
 TimeSpan ts = stopWatch.Elapsed;

推荐阅读