欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > C#并行使用及性能对比

C#并行使用及性能对比

2024/12/27 5:13:27 来源:https://blog.csdn.net/yunxiaobaobei/article/details/144111841  浏览:    关键词:C#并行使用及性能对比

此文用于记录测试C#并行处理与单线程执行耗时操作的性能对比


static int count = 100;static Stopwatch sw = new Stopwatch();static void Main(string[] args){Console.WriteLine("Hello, World!");for (int i = 0; i < 5; i++){orderExec();ParallerExec2();Console.ReadLine();}}private static void orderExec(){sw.Restart();var list = Enumerable.Range(0, count).ToList();string imagePath = "E:\\image";string[] iamges = Directory.GetFiles(imagePath).Where(x => x.EndsWith("bmp")).ToArray();for (int i = 0; i < list.Count; i++){DealImage(iamges[i], SKColors.Red, new SKPoint(100, 100));}Console.WriteLine($"执行耗时:{sw.Elapsed.TotalSeconds}");}private static void ParallerExec2()
{int[] numbers = Enumerable.Range(0, count).ToArray(); Stopwatch stopwatch = new Stopwatch();stopwatch.Start();int physicalCoreCount = Environment.ProcessorCount;int parallelCount = physicalCoreCount / 2;Console.WriteLine("虚拟处理器数量:{0}, 并行度:{1}", physicalCoreCount, parallelCount);// 设置并行度var options = new ParallelOptions { MaxDegreeOfParallelism = parallelCount };string imagePath = "E:\\image";string[] iamges = Directory.GetFiles(imagePath).Where(x => x.EndsWith("bmp")).ToArray();Parallel.ForEach(numbers, options, number =>{DealImage(iamges[number],SKColors.Blue, new SKPoint(200, 200));});stopwatch.Stop();Console.WriteLine($"执行耗时: {stopwatch.Elapsed.TotalSeconds}");}private static void DealImage(string file, SKColor color, SKPoint point)
{SKBitmap pic = SKBitmap.Decode(file);SKCanvas canvas = new SKCanvas(pic);canvas.DrawCircle(point.X, point.Y, 100, new SKPaint() { Color = color, Style = SKPaintStyle.Fill });using var stream = File.OpenWrite(file);pic.Encode(SKEncodedImageFormat.Png, 100).SaveTo(stream);stream.Close();stream.Dispose();canvas.Dispose(); 
}

测试处理100张图(1280x1024)的耗时对比,并行处理的耗时明显比单线程处理的更快,同时并行处理CPU占用会很高,建议设置并行数量时尽量比逻辑处理器个数要少,给其他进程让出部分CPU

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com