Speed up Matrix Addition in C#

前端 未结 15 1161
北荒
北荒 2021-02-05 22:48

I\'d like to optimize this piece of code :

public void PopulatePixelValueMatrices(GenericImage image,int Width, int Height)
{            
        for (int x = 0;         


        
15条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 23:02

    Although it's a micro-optimization and thus may not add much you might want to study what the likelihood is of getting a zero when you do

    Byte  pixelValue = image.GetPixel(x, y).B;
    

    Clearly, if pixelValue = 0 then there's no reason to do the summations so your routine might become

    public void PopulatePixelValueMatrices(GenericImage image,int Width, int Height)
      {
      for (int x = 0; x < Width; x++)
        {
        for (int y = 0; y < Height; y++)
          {
           Byte  pixelValue = image.GetPixel(x, y).B;
    
           if(pixelValue != 0)
             {
             this.sumOfPixelValues[x, y] += pixelValue;
             this.sumOfPixelValuesSquared[x, y] += pixelValue * pixelValue;
             }}}}
    

    However, the question is how often you're going to see pixelValue=0, and whether the saving on the compute-and-store will offset the cost of the test.

提交回复
热议问题