iphone - iPhone 上两个数组之间按位与的最快方法?

标签 iphone optimization neon

我有两个图像 block 存储为一维数组,并在它们的元素之间执行以下按位与运算。

int compare(unsigned char *a, int a_pitch, 
            unsigned char *b, int b_pitch, int a_lenx, int a_leny) 
{
    int overlap =0 ;

    for(int y=0; y<a_leny; y++) 
        for(int x=0; x<a_lenx; x++) 
        {
            if(a[x + y * a_pitch] & b[x+y*b_pitch]) 
                overlap++ ;
        }
    return overlap ;
}

实际上,我必须执行这项工作大约 220,000 次,因此在 iPhone 设备上它变得非常慢。

如何在 iPhone 上加速这项工作?

我听说 NEON 很有用,但我不太熟悉它。另外NEON好像没有按位AND...

最佳答案

选项 1 - 在平台的 native 宽度下工作(将 32 位读取到寄存器中,然后在该寄存器上执行操作比一次读取并比较一个字节的数据更快):

int compare(unsigned char *a, int a_pitch, 
            unsigned char *b, int b_pitch, int a_lenx, int a_leny) 
{
    int overlap = 0;
    uint32_t* a_int = (uint32_t*)a;
    uint32_t* b_int = (uint32_t*)b;

    a_leny = a_leny / 4;
    a_lenx = a_lenx / 4;
    a_pitch = a_pitch / 4;
    b_pitch = b_pitch / 4;

    for(int y=0; y<a_leny_int; y++) 
        for(int x=0; x<a_lenx_int; x++) 
        {
            uint32_t aVal = a_int[x + y * a_pitch_int];
            uint32_t bVal = b_int[x+y*b_pitch_int];
            if (aVal & 0xFF) & (bVal & 0xFF)
                overlap++;
            if ((aVal >> 8) & 0xFF) & ((bVal >> 8) & 0xFF)
                overlap++;
            if ((aVal >> 16) & 0xFF) & ((bVal >> 16) & 0xFF)
                overlap++;
            if ((aVal >> 24) & 0xFF) & ((bVal >> 24) & 0xFF)
                overlap++;
        }
    return overlap ;
}

选项 2 - 使用启发式方法,通过较少的计算获得近似结果(如果 101 次重叠和 100 次重叠之间的绝对差异对您的应用程序并不重要,那么这是一个好方法):

int compare(unsigned char *a, int a_pitch, 
            unsigned char *b, int b_pitch, int a_lenx, int a_leny) 
{
    int overlap =0 ;

    for(int y=0; y<a_leny; y+= 10) 
        for(int x=0; x<a_lenx; x+= 10) 
        {
            //we compare 1% of all the pixels, and use that as the result
            if(a[x + y * a_pitch] & b[x+y*b_pitch]) 
                overlap++ ;
        }
    return overlap * 100;
}

选项 3 - 用内联汇编代码重写函数。这件事你得靠你自己了。

关于iphone - iPhone 上两个数组之间按位与的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6338423/

相关文章:

iphone - 如何比较图像字符串(名称?)并更改图像

python - 控制 python 导入以减少大小和开销

optimization - 如何优化邻居访问的OpenCL代码?

c - 快速 ARM NEON memcpy

ipad - 如何在 iPad A4 处理器上执行整数 SIMD 操作?

math - 使用 NEON 对 ARM 汇编中的四字向量中的所有元素求和

iphone - 任何关于如何从 uitabbarcontroller 访问 viewcontroller 的代码示例?

iphone - 什么是 Setter 和 Getter?

iphone - 倒计时 UILabel 不会递减

assembly - 移位指令比 IMUL 指令快吗?