user5480694
user5480694

Reputation:

Fast search/replace of matching single bytes in a 8-bit array, on ARM

I develop image processing algorithms (using GCC, targeting ARMv7 (Raspberry Pi 2B)).

In particular I use a simple algorithm, which changes index in a mask:

void ChangeIndex(uint8_t * mask, size_t size, uint8_t oldIndex, uint8_t newIndex)
{
    for(size_t i = 0; i < size; ++i)
    {
        if(mask[i] == oldIndex)
            mask[i] = newIndex;
    }
}

Unfortunately it has poor performance for the target platform.

Is there any way to optimize it?

Upvotes: 6

Views: 845

Answers (1)

ErmIg
ErmIg

Reputation: 4038

The ARMv7 platform supports SIMD instructions called NEON. With use of them you can make you code faster:

#include <arm_neon.h>

void ChangeIndex(uint8_t * mask, size_t size, uint8_t oldIndex, uint8_t newIndex)
{
    size_t alignedSize = size/16*16, i = 0;

    uint8x16_t _oldIndex = vdupq_n_u8(oldIndex);
    uint8x16_t _newIndex = vdupq_n_u8(newIndex);

    for(; i < alignedSize; i += 16)
    {
        uint8x16_t oldMask = vld1q_u8(mask + i); // loading of 128-bit vector
        uint8x16_t condition = vceqq_u8(oldMask, _oldIndex); // compare two 128-bit vectors
        uint8x16_t newMask = vbslq_u8(condition, _newIndex, oldMask); // selective copying of 128-bit vector
        vst1q_u8(mask + i, newMask); // saving of 128-bit vector
    }

    for(; i < size; ++i)
    {
        if(mask[i] == oldIndex)
            mask[i] = newIndex;
    }
}

Upvotes: 13

Related Questions