C++模数乘以2的表现

Col*_*ett 1 c++ performance modulus

我想知道当通过2运算执行整数模数时,典型编译器的程序集减少是什么:

const char* integer_string = "300"; // avoid compiler optimization
int i = atoi(integer_string);
int b = i % 2; // the line in question
Run Code Online (Sandbox Code Playgroud)

我想,编译器可以把它变成一个按位操作来检查最后一位(1s位置),但是它会这样做吗?

NPE*_*NPE 8

这个问题只在特定编译器,平台,优化选项等环境中才有意义.

我的编译器(gcc 4.7.2on x86_64)在启用-O3优化时执行此操作:

    andl    $1, %esi
Run Code Online (Sandbox Code Playgroud)

  • @Matt:(1)编译成程序集(`-S`如果使用`gcc`).(2)检查组件. (2认同)