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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

破浪征程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值