optimization - Why doesn't my C++ compiler optimize these memory writes away? -
i created program. nothing of interest use processing power.
looking @ output objdump -d, can see 3 rand calls , corresponding mov instructions near end when compiling o3 .
why doesn't compiler realize memory isn't going used , replace bottom half while(1){}? i'm using gcc, i'm interested in required standard.
/* * create program nothing except slow down computer. */ #include <cstdlib> #include <unistd.h> int getrand(int max) { return rand() % max; } int main() { (int thread = 0; thread < 5; thread++) { fork(); } int len = 1000; int *garbage = (int*)malloc(sizeof(int)*len); (int x = 0; x < len; x++) { garbage[x] = x; } while (true) { garbage[getrand(len)] = garbage[getrand(len)] - garbage[getrand(len)]; } }
because gcc isn't smart enough perform optimization on dynamically allocated memory. however, if change garbageto local array instead, gcc compiles loop this:
.l4: call rand call rand call rand jmp .l4 this calls rand repeatedly (which needed because call has side effects), optimizes out reads , writes.
if gcc smarter, optimize out randcalls, because side effects affect later randcalls, , in case there aren't any. however, sort of optimization waste of compiler writers' time.
Comments
Post a Comment