Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
            //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?"

like image 586
nightWatcher Avatar asked May 10 '26 09:05

nightWatcher


2 Answers

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);   }
like image 103
slippyr4 Avatar answered May 12 '26 23:05

slippyr4


  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.

like image 43
Henrik Avatar answered May 13 '26 00:05

Henrik