1
class modifier {
private:
    float origin = 0.0, range = 1.0;
public:
    int map(float input) {
        return static_cast<int>((input - origin) / range);
    }
};

modifier mod;
mod.origin = std::rand();
mod.range = std::rand(); // example only
for(std::ptrdiff_t y = 0; y < h; ++y)
for(std::ptrdiff_t x = 0; x < w; ++x)
    out[x][y] = mod.map( in[x][y] );

Are C++ compilers (GCC, Clang) able to optimize code like this so that the non-static data members origin and range remain stored in registers during the iterations, instead of being looked up again each time?

tmlen
  • 8,533
  • 5
  • 31
  • 84
  • 1
    I would go and inspect the actual assembly output for specific optimization level, I'm pretty sure a compiler will be able to output such code. – πάντα ῥεῖ Apr 05 '16 at 15:59
  • Why ask us? Ask your compiler (it will reply in ASM). – SergeyA Apr 05 '16 at 16:02
  • I tried with VS2015 and the answer is yes. The compiler use xmm register. – alangab Apr 05 '16 at 16:09
  • Check out this [example of what an optimizer can do](http://stackoverflow.com/a/11639305/597607) and you might no longer worry about a couple of de facto constants. – Bo Persson Apr 05 '16 at 16:13
  • If `origin` and `range` are never written to, the compiler may treat them as constants, decide that the operation is an identity mapping (`(input-0.0)/1.0`) and eliminate the computation altogether. – Peter - Reinstate Monica Apr 05 '16 at 16:16
  • `origin` and `range` can be changed to a runtime-defined value before the loop – tmlen Apr 05 '16 at 16:19
  • Yes they can....the compiler can basically do what ever it wants as long as the variable is not `volatile` – DarthRubik Apr 16 '16 at 17:36

0 Answers0