简体   繁体   English

最小化C ++中的分支-如果值不为零,则递增

[英]Minimize branching in C++ - Increment if value is non-zero

I have the following nested for-loop: 我有以下嵌套的for循环:

for(k = 0; k < n; ++k) {
    for(m = 0; m < n; ++m) {
        /* other logic altering a */
        if(a[index] != 0) count++;
    }
}

where a contains uint32_t . 其中a包含uint32_t Since n can be quite large (but constant), and this is the only branch (besides comparing k and m with n ), I would like to optimize this away. 由于n可以很大(但是恒定),并且这是唯一的分支(除了将kmn进行比较),我想对其进行优化。

The distribution of zero and non-zero in a can be considered uniformly random. 的零和非零在分配a可以被认为是均匀随机的。

My first approach was 我的第一个方法是

count += a[index] & 1;

but then count would only be incremented for all odd numbers. 但是对于所有奇数, count只会增加。

In addition: I also have a case where a contains bool , but according to C++ Conditionals true and false are defined as non-zero and zero, which basically are equivalent to the above problem. 另外:我也有一种情况,其中a包含bool ,但是根据C ++,条件 truefalse定义为非零和零,这基本上等同于上述问题。

As stated in the comments for the question if(a[index] != 0) count++; 如问题注释中所述if(a[index] != 0) count++; does not produce a branch (in this case), which was somewhat verified in the assembly. 不会产生分支(在这种情况下),该分支已在程序集中进行了验证。

For the sake of the completeness an equivalent to the mentioned statement are count += a[index] != 0; 为了完整起见,与上述语句等效的是count += a[index] != 0; (according to standard §4.7 [conv.integral]) (根据标准§4.7[conv.integral])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM