Can I compute pow(10,x) at compile

Is it possible to compute pow(10,x) at compile time?

I've got a processor without floating point support and slow integer division. I'm trying to perform as many calculations as possible at compile time. I can dramatically speed up one particular function if I pass both x and C/pow(10,x) as arguments (x and C are always constant integers, but they are different constants for each call). I'm wondering if I can make these function calls less error prone by introducing a macro which does the 1/pow(10,x) automatically, instead of forcing the programmer to calculate it?

Is there a pre-processor trick? Can I force the compiler optimize out the library call?


You can use the scientific notation for floating point values which is part of the C language. It looks like that:

e = 1.602E-19   // == 1.602 * pow(10, -19)

The number before the E ( the E maybe capital or small 1.602e-19 ) is the fraction part where as the (signed) digit sequence after the E is the exponent part. By default the number is of the type double , but you can attach a floating point suffix ( f , F , l or L ) if you need a float or a long double .

I would not recommend to pack this semantic into a macro:

  • It will not work for variables, floating point values, etc.
  • The scientific notation is more readable.

  • There are very few values possible before you overflow int (or even long). For clarities sake, make it a table!

    edit: If you are using floats (looks like you are), then no it's not going to be possible to call the pow() function at compile time without actually writing code that runs in the make process and outputs the values to a file (such as a header file) which is then compiled.


    GCC will do this at a sufficiently high optimization level (-O1 does it for me). For example:

    #include <math.h>
    
    int test() {
            double x = pow(10, 4);
            return (int)x;
    }
    

    Compiles at -O1 -m32 to:

            .file   "test.c"
            .text
    .globl test
            .type   test, @function
    test:
            pushl   %ebp
            movl    %esp, %ebp
            movl    $10000, %eax
            popl    %ebp
            ret
            .size   test, .-test
            .ident  "GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3"
            .section        .note.GNU-stack,"",@progbits
    

    This works without the cast as well - of course, you do get a floating-point load instruction in there, as the Linux ABI passes floating point return values in FPU registers.

    链接地址: http://www.djcxy.com/p/85724.html

    上一篇: 使用常数双指数优化幂的和

    下一篇: 我可以在编译时计算pow(10,x)