Speed up Matrix Addition in C#

前端 未结 15 1474
北荒
北荒 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:11

    This is a classic case of micro-optimisation failing horribly. You're not going to get anything from looking at that loop. To get real speed benefits you need to start off by looking at the big picture:-

    • Can you asynchronously preload image[n+1] whilst processing image[n]?
    • Can you load just the B channel from the image? This will decrease memory bandwidth?
    • Can you load the B value and update the sumOfPixelValues(Squared) arrays directly, i.e. read the file and update instead of read file, store, read, update? Again, this decreases memory bandwidth.
    • Can you use one dimensional arrays instead of two dimensional? Maybe create your own array class that works either way.
    • Perhaps you could look into using Mono and the SIMD extensions?
    • Can you process the image in chunks and assign them to idle CPUs in a multi-cpu environment?

    EDIT:

    Try having specialised image accessors so you're not wasting memory bandwidth:

    public Color GetBPixel (int x, int y)
    {
        int offsetFromOrigin = (y * this.stride) + (x * 3);
        unsafe
        {
            return this.imagePtr [offsetFromOrigin + 1];
        }
    }
    

    or, better still:

    public Color GetBPixel (int offset)
    {
        unsafe
        {
            return this.imagePtr [offset + 1];
        }
    }
    

    and use the above in a loop like:

    for (int start_offset = 0, y = 0 ; y < Height ; start_offset += stride, ++y)
    {
       for (int x = 0, offset = start_offset ; x < Width ; offset += 3, ++x)
       {
          pixel = GetBPixel (offset);
          // do stuff
       }
    }
    

提交回复
热议问题