如何测量并行处理中运行的每个任务的时间?

问题描述

我有一组项目并根据批量大小拆分项目,例如 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);
    }
}

解决方法

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

并且您可以在要测量其执行时间的函数中使用 stopwatch

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