c - GCC optimization? -
i'm using gcc 4.8.1. i'm trying benchmark speed of code putting nested loops, in example below. whenever so, executes in minimal amount of time (like .02 seconds), -03 or without optimizations, , regardless of how many iterations there are. reasons this? i'm sure it's working fine because values correct , if use printf
within loops, runs expected.
int main() { int i,j,k; int var; int big_num = 1000000; int x[1]; (i = 0;i<big_num;++i){ (j = 0;j<big_num;++j){ (k = 0;k<big_num;++k){ // short code fragment such as: var = - j + k; x[0] = var; } } } return 0; }
not more true edited question: your code declaring single-element array int x[1];
, accessing out of bounds index (the index should less 1 non negative, can 0) x[1]
; typical undefined behavior , compiler can legally optimize emitting kind of code.
btw, gcc 4.9 (on debian/sid/x86-64) is (rightfully) optimizing code empty main
(since no useful computation happens) ; can check out compiling gcc -fverbose-asm -o2 -s
, looking generated *.s
assembly file ; if curious various internal representations during optimization passes, compile -fdump-tree-all
; alter compiler's behavior (or add inspecting passes), e.g. extending melt
you make computation meaningful replacing x[0] = var;
x[0] += var;
, ending main
side effect on x[0]
, e.g. printf("%d\n", x[0]);
or return x[0] != 0;
. compiler generate loop (it might compute result of loop @ compile time, don't think gcc clever enough).
at last, typical current microprocessors out-of-order & superscalar execute more 1 instruction per cycle (with clock frequency of e.g. @ least 2ghz). running several billions basic operations per second. need benchmark last more half second (otherwise measurement not meaningful enough) , repeat several times benchmark. need code benchmarking code several dozens billions (i.e. more 1010) elementary c operations executed. , need code useful (with side-effects or resulting computation used elsewhere), otherwise compiler optimize removing it. also, benchmarking code should take input (otherwise compiler might lot of computation @ compile-time). in case might initialize bignum
like
int main (int argc, char**argv) { int big_num = (argc>1)?atoi(argv[1]):1000000;
Comments
Post a Comment