并发Graphics.RotateTransform操作的性能较差

本文关键字:性能 操作 Graphics RotateTransform 并发 | 更新日期: 2023-09-27 18:19:44

为什么在多个线程上运行并行Graphics.RotateTransform操作时,速度没有显著提高?

这个例子展示了边际性能提升:

    static Bitmap rotate(Bitmap bitmap, float angle)
    {
        Bitmap rotated = new Bitmap(bitmap.Width, bitmap.Height);
        using (Graphics g = Graphics.FromImage(rotated))
        {
            g.TranslateTransform((float)bitmap.Width / 2, (float)bitmap.Height / 2);
            g.RotateTransform(angle);
            g.TranslateTransform(-(float)bitmap.Width / 2, -(float)bitmap.Height / 2);
            g.DrawImage(bitmap, new Point(0, 0));
        }
        return rotated;
    }
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        string fileName = Path.GetTempFileName();
        client.DownloadFile("http://i.imgur.com/Vwiul.png", fileName);
        Bitmap original = new Bitmap(fileName);
        DateTime start = DateTime.Now;
        rotateSingleThread(original);
        TimeSpan length = DateTime.Now - start;
        Console.WriteLine(string.Format("Single thread rotate took {0} ms", (int)length.TotalMilliseconds));
        start = DateTime.Now;
        rotateMultiThread(original);
        length = DateTime.Now - start;
        Console.WriteLine(string.Format("Multiple thread rotate took {0} ms", (int)length.TotalMilliseconds));
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
    static void rotateSingleThread(Bitmap original)
    {
        for (float a = 0; a < 360; a += 0.1F)
        {
            Bitmap rotated = rotate(original, a);
            rotated.Dispose();
        }
    }
    static void rotateMultiThread(Bitmap original)
    {
        int threadCount = Environment.ProcessorCount;
        int groupSize = 360 / threadCount;
        Thread[] threads = new Thread[threadCount];
        Bitmap[] bitmaps = new Bitmap[threadCount];
        for (int x = 0; x < threadCount; x++)
        {
            bitmaps[x] = new Bitmap(original);
            threads[x] = new Thread(delegate(object i)
            {
                int min = (int)i * groupSize; int max = min + groupSize;
                if ((int)i == threadCount - 1) max = 360;
                for (float a = min; a < max + 1; a+= 0.1F)
                {
                    Bitmap rotated = rotate(bitmaps[(int)i], a);
                    rotated.Dispose();
                }
            });
            threads[x].Start(x);
        }
        for (int x = 0; x < threadCount; x++) threads[x].Join();
    }

我可以做些什么来提高执行并发Graphics.RotateTransform操作的速度?

并发Graphics.RotateTransform操作的性能较差

问题是那些GDI+调用每个进程(而不是每个线程)的块,所以即使线程并行运行,对graphics....的调用也会导致其他线程阻塞。这意味着它最终几乎是连续处理的。

有关解决方法,请参阅下面问题中的各种答案,其中最重要的一个建议创建单独的流程。看起来您最终可能只是创建了一个辅助命令行实用程序或其他什么。您甚至可以将stdin和stdout巧妙地连接起来,这样您就可以传递图像进行旋转,并在没有IO操作的情况下返回新图像。

并行GDI+图像大小调整.net

我没有答案,但有一些想法可能会有所帮助:

  1. 您的线程是否在多个处理器上运行
  2. 你是如何衡量业绩的?请记住,UI渲染始终单螺纹