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