c# - 如何测量并行处理中运行的每个任务的时间?
问题描述
我有一组项目并根据批量大小(例如 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 的
另一个重载: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;
推荐阅读
- javascript - 如何一次性使用点击处理程序创建 DOM 元素?
- javascript - 使用 ES 6 方法转换 JSON 数组
- jenkins - 如何强制詹金斯作业等到所有作业循环执行
- ajax - 如何在基于 ajax 的 MVC.NET Web 应用程序中管理页面导航
- nestjs - Prisma 种子未执行
- linux - 在 Linux Plesk 服务器上,Laravel 存储链接显示为断开的链接
- javascript - 鳗鱼函数返回null
- bash - 在文本文件中插入或更新一行
- php - 无法让 PHP 在 Docker 容器中与 SQL Server 一起工作
- php - Laravel如何替换不同服务器上的本地数据库表SELECT FROM外部数据库表?