c++ - bool判断这么慢?

标签 c++ c optimization sse

<分区>

我正在优化函数,我尝试了各种方法甚至sse,并修改了代码以从不同的位置返回以查看计算时间跨度但最后我发现大部分时间都花在了bool判断上。即使我用一个简单的添加操作替换了 if 语句中的所有代码,它仍然花费 6000 毫秒。

我的平台是 gcc 4.7.1 e5506 cpu。它的输入'a'和'b'是一个1000size的int数组,'asize','bsize'是对应的数组大小。 MATCH_MASK = 16383,我运行函数100000次来统计一个时间跨度。这个问题有什么好主意吗。谢谢!

   if (aoffsets[i] && boffsets[i])  // this line costs most time

代码:

uint16_t aoffsets[DOUBLE_MATCH_MASK] = {0}; // important! or it will only be right on the first time
uint16_t* boffsets = aoffsets + MATCH_MASK;
uint8_t* seen = (uint8_t *)aoffsets;
auto fn_init_offsets = [](const int32_t* x, int n_size, uint16_t offsets[])->void
{
    for (int i = 0; i < n_size; ++i)
        offsets[MATCH_STRIP(x[i])] = i;
};
fn_init_offsets(a, asize, aoffsets);
fn_init_offsets(b, bsize, boffsets);

uint8_t topcount = 0;
int topoffset = 0;
{
    std::vector<uint8_t> count_vec(asize + bsize + 1, 0);   // it's the fastest way already, very near to tls
    uint8_t* counts = &(count_vec[0]);
            //return aoffsets[0];   // cost 1375 ms
    for (int i = 0; i < MATCH_MASK; ++i)
    {
        if (aoffsets[i] && boffsets[i])  // this line costs most time
        {
                            //++affsets[i];  // for test
            int offset = (aoffsets[i] -= boffsets[i]);
            if ((-n_maxoffset <= offset && offset <= n_maxoffset))
            {
                offset += bsize;
                uint8_t n_cur_count = ++counts[offset];
                if (n_cur_count > topcount)
                {
                    topcount = n_cur_count;
                    topoffset = offset;
                }
            }
        }
    }
}
    return aoffsets[0];   // cost 6000ms

最佳答案

首先,memaligned 缓冲区的 memset(count_vec,0, N); 胜过 std::vector 30%。

你可以尝试使用无分支表达式(aoffsets[i] * boffsets[i])同时计算一些不用的表达式:offset = aoffset[i]-boffset[i] ;偏移量+bsize; offset+n_maxoffset;.

根据 offset 的典型范围,人们可能会想计算 (offset+bsize) 的最小值/最大值以限制下一次迭代所需的 memset(count_vec):不需要清除已经为零的值。

正如 philipp 所指出的,交错操作是很好的——再一次,可以从 uint32_t aboffset[N] 中同时读取 aoffset[i] 和 boffset[i];通过一些巧妙的位掩码(为 aoffset[i]、aoffset[i+1] 生成更改掩码),可以使用纯 c 中的 64 位模拟 SIMD(直到直方图累积部分)并行处理 2 组。

关于c++ - bool判断这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505788/

相关文章:

c - 像算术运算符的操作数这样的临时值是否放在堆栈中?

c - 为不同数据类型分配的内存是否取决于体系结构?

c++ - C++程序优化

c++ - 绘制多边形网格时 Opengl 性能问题

c++ - 指向堆上数组的指针的地址

c++ - vim c++ 断行

c++ - glBuffer 使用一种数据样式而不使用另一种样式,为什么?

c++ - 修复涉及派生类和静态类的 C++ 内存泄漏

c - 使用 ptrace 查找 main 函数的开始

html - 如何优化包含大量图像的超长页面?