Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对优化这段代码有什么建议吗?_C#_Optimization - Fatal编程技术网

C# 对优化这段代码有什么建议吗?

C# 对优化这段代码有什么建议吗?,c#,optimization,C#,Optimization,我已经根据给出的答案编写了一个代码 我的示例代码如下 void Process(int i) { input = (Bitmap)Bitmap.FromFile(@"filepath.bmp"); Bitmap temp = new Bitmap(input.Width, input.Height, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromI

我已经根据给出的答案编写了一个代码

我的示例代码如下

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++;
       }
   }
}
所以我尝试将图像从rgb32转换为rgb24。但它在处理上花费的时间比线程休眠的时间要多。这只是一个示例代码。帮我回答这个问题 “如何优化进程(int i)以在20毫秒或少于100毫秒的时间内执行?”

  • 图形与COM+背道而驰。很慢。使用WPF附带的媒体名称空间

  • 剩下的时间;视情况而定。输入大小、机器配置(dx版本、图形卡)、使用C和p/invoke的技能。

    由于要制作相同大小的图像,可以删除以下行

    g、 清晰(颜色:红色)


    它可能没有多大区别,但可以减少您的时间

    您可能希望并行运行它-虽然每个映像仍需要相同的时间,但您可以一次处理多个映像(假设您的CPU中有多个内核)

    可以显著改进您的代码:-

  • 您的“输入”图像始终是相同的图像。但每次调用Process()时都会加载它。将其设为成员,并仅加载一次

  • 每次调用Process()时都会分配“temp”位图,同样,也不需要这样做。将其设为成员,并分配一次

  • 您不会处理任何图形对象。位图应该在使用完毕后进行处理,图形也应该如此

  • 这并不是一个真正的性能问题,但是您的for循环非常奇怪,而且不可读。为什么要尝试重新创建内置的语言结构?你怎么了

    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);   }
    

    @Scrum Meister:)我不知道该说什么:谁在给timer_Ex打电话?多久一次?如果问题真的是处理时间比睡眠时间长,那么您应该停止处理方法中的计时器,并在完成后重新启动它。由于时间取决于正在处理的文件以及计算机上正在进行的其他操作,因此无法保证在70毫秒内速度会更快。因此,请在流程方法的开头停止计时器,并在结尾重新启动。非常感谢您的建议。关于循环,我真是太蠢了,竟然有这样的循环。也谢谢你的提示:)