【问题标题】:Why is using variables so much faster than just using the value?为什么使用变量比只使用值快得多?
【发布时间】:2023-01-02 03:00:27
【问题描述】:

我有这段代码基本上通过了一个非常大的图像,两种看起来超级相似的方式有 70% 的速度差异。 第一个是快速的,大约需要 10 秒

 if (clusterPntr[col] == i) {
                        
                        /* Calculate the location of the relevant pixel (rows are flipped) */
                        pixel = bmp->Data + ( ( bmp->Header.Height - row - 1 ) * bytes_per_row + col  * bytes_per_pixel );
                        /* Get pixel's RGB values */
                        b=pixel[0];
                        g=pixel[1];
                        r=pixel[2];
                        totr += r; 
                        totg += g;
                        totb += b;
                        sizeCluster++;

                    }

第二个需要 17 秒

 if (clusterPntr[col] == i) {
                    
                    /* Calculate the location of the relevant pixel (rows are flipped) */
                    pixel = bmp->Data + ( ( bmp->Header.Height - row - 1 ) * bytes_per_row + col  * bytes_per_pixel );
                    /* Get pixel's RGB values */

                    //why is this SO MUCH SLOWER 
                    totr += pixel[2]; 
                    totg += pixel[1];
                    totb += pixel[0];
                    sizeCluster++;

                }

我认为问题在于缓存以及一个版本如何使用寄存器而另一个版本使用数据数组。 CPU 是 M1 pro,因此 ARM 架构可能也有一些作用

【问题讨论】:

  • 您正在以不同的顺序访问通道,这会影响您的内存访问模式。尝试按顺序访问频道。

标签: c loops image-processing optimization


【解决方案1】:

您的代码中唯一真正发生变化的是您正在访问索引 2,然后是索引 1,然后是索引 0,而不是索引 0、1 和 2。

平均而言,第一个版本 (2,1,0) 创建 3 个缓存默认值。第二个只创建一个。我会尝试:

    totb += pixel[0];
    totg += pixel[1];
    totr += pixel[2]; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 2015-06-27
    • 2011-10-19
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多