Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do math functions of constant expressions get pre-calculated at compile time?

I tend to use math functions of constant expressions for convinience and coherence (i.e log(x)/log(2) instead of log(x)/0.3...). Since these functions aren't actually a part of the language itself, neither are they defined in math.h (only declared), will the constant ones get precalculated at compile time, or will they be wastefully calculated at runtime?

like image 548
cvb Avatar asked Jan 12 '10 14:01

cvb


People also ask

Is constant expressions are evaluated at compile time?

A constant expression gets evaluated at compile time, not run time, and can be used in any place that a constant can be used. The constant expression must evaluate to a constant that is in the range of representable values for that type.

How do you calculate compilation time?

Hence taking the difference of starts and ends will give you execution time of test_case() in second multiplied by CLOCKS_PER_SEC . CLOCKS_PER_SEC is the number of clock ticks per second. Compile time calculation can be done using template metaprogramming.

What is a constant expression in C++?

A constant expression is an expression that can be evaluated at compile time. Constants of integral or enumerated type are required in several different situations, such as array bounds, enumerator values, and case labels. Null pointer constants are a special case of integral constants.


1 Answers

It depends on the compiler and the optimization flags. As @AndrewyT points out, GCC has the ability to specify which functions are constant and pure via attributes, and in this case the answer is positive, it will inline the result, as you can easily check:

$ cat constant_call_opt.c 
#include <math.h>

float foo() {
        return log(2);
}

$ gcc -c constant_call_opt.c -S

$ cat constant_call_opt.s 
        .file   "constant_call_opt.c"
        .text
.globl foo
        .type   foo, @function
foo:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $4, %esp
        movl    $0x3f317218, %eax
        movl    %eax, -4(%ebp)
        flds    -4(%ebp)
        leave
        ret
        .size   foo, .-foo
        .ident  "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
        .section        .note.GNU-stack,"",@progbits

no function call there, just loads a constant (0x3f317218 == 0.69314718246459961 == log(2))

Althought I have not any other compiler at hand to try now, I think you could expect the same behaviour in all the major C compilers out there, as it's a trivial optimization.

like image 127
fortran Avatar answered Sep 22 '22 06:09

fortran