开发者

Any suggestions for optimizing this code?

I have written a code from the answer given here

My sample code is as follows

void Process(int i)
{
    input = (Bitmap)Bitmap.FromFile(@"filepath.bmp");

    Bitmap temp = new Bitmap(input.Width, input.Height, 
                             PixelFormat.Format24bppRgb);
    Graphics g = Graphics.FromImage(temp);
    g.Clear(Color.Red);
    g.DrawImage(input, Point.Empty);

    temp.Save(stream, ImageFormat.Bmp);
    //I need this stream thats further processing
}

void timer_Ex()
{
    int i = 11;
    for (; ; )
    {
      if (i == 335) break;
      else
      {
         st.Start();
         Process(i);
         st.Stop();    
         Console.WriteLine(st.ElapsedMilliseconds.ToString()开发者_如何学Go);
            //This time is more than the time in which thread sleeps
         st.Reset();                       
         Thread.Sleep(70);                     
         i++;
       }
   }
}

So I am trying to convert image from rgb32 to rgb24. But it takes more time on processing than the time in which thread sleeps. Its just a sample code. So just help me with this question "How can i optimize process(int i) to execute in 20 ms or less than 100 ms?"


Things to dramatically improve your code:-

  1. your "input" image is always the same image. But you load it every time Process() is called. Make it a member, and load it once only.

  2. Your "temp" bitmap is allocated every time you call Process(), again it does not need to be. Make it a member, and allocate it once.

  3. You don't dispose of any of your Graphics objects. Bitmaps should be disposed when you are done with them, as should Graphics.

Not really a performance thing, but your for loop is very very odd, and unreadable. Why do you try to reinvent language constructs that are built in? what is wrong with

for (int i=11; i != 335 ; i++)
{

     st.Start();
     Process(i);
     st.Stop();    
     Console.WriteLine(st.ElapsedMilliseconds.ToString());
        //This time is more than the time in which thread sleeps
     st.Reset();                       
     Thread.Sleep(70);   }


  1. Graphics goes against COM+. It's slow. Use the Media-namespace that came with WPF.

For the rest of it; it depends. Input size, machine configuration (dx version, graphics card), your skills with C and p/invoke.


Since you are going to make the same size of image the following line can be removed

g.Clear(Color.Red);

It may not make much difference but it can reduce your time


You might want to run it in parallel - whilst each image will still take the same amount of time, you'll be able to process more at once (assuming you have more than 1 core in your CPU)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜