cost of fprintf

后端 未结 4 366
-上瘾入骨i
-上瘾入骨i 2021-01-15 05:31

I am developing an embedded application in C++ for a platform with limited code/data RAM, but rather unlimited RAM for filesystem usage.

While looking for reducing t

4条回答
  •  滥情空心
    2021-01-15 06:07

    In embedded systems, printf can sometimes drag in all the floating point support for format strings like %f.

    More intelligent environments will make the floating point options for printf an optional thing.

    But even for integers, there's a lot of general purpose code in printf and you may find it's more compact to write your own routines, tailored to your specific needs, like:

    outInt (char *buff, int intVal);
    outChr (char *buff, char chVal);
    outStr (char *buff, char *strVal);
    

    and so on, for writing to buffers, then outBuff (char *buff) for sending it to a file or standard output.


    For example, if you control the data being used (no string overflow, 16-bit twos complement integers and such), you can use the following functions:

    #include 
    #include 
    #include 
    
    void outChr (char *buff, char chVal) {
        *buff++ = chVal;
        *buff = '\0';
    }
    
    void outStr (char *buff, char *strVal) {
        strcpy (buff, strVal);
    }
    

     

    void outInt (char *buff, int intVal) {
        int divisor = 10000, printing = 0;
    
        // Special cases.
    
        if (intVal == -32768) { outStr (buff, "-32768"); return; }
        if (intVal ==      0) { outChr (buff,      '0'); return; }
    
        // Handle negatives.
    
        if (intVal < 0) { outChr (buff++, '-'); intVal = -intVal; }
    
        // Handle non-zero positives <= 32767.
    
        while (divisor > 0) {
            if ((intVal >= divisor) || printing) {
                outChr (buff++, "0123456789"[intVal/divisor]);
                printing = 1;
            }
            intVal = intVal % divisor;
            divisor /= 10;
        }
    }
    

     

    int main (int argc, char *argv[]) {
        char buff[1000];
        int i;
        for (i = 1; i < argc; i++) {
            outInt (buff, atoi (argv[i]));
            printf ("[%s] -> [%s]\n", argv[i], buff);
        }
        return 0;
    }
    

    Running this with:

    pax$ tstprg 32767 10000 9999 10 9 1 0 -1 -9 -10 -99 -10000 -32767 -32768
    

    outputs:

    [32767] -> [32767]
    [10000] -> [10000]
    [9999] -> [9999]
    [10] -> [10]
    [9] -> [9]
    [1] -> [1]
    [0] -> [0]
    [-1] -> [-1]
    [-9] -> [-9]
    [-10] -> [-10]
    [-99] -> [-99]
    [-10000] -> [-10000]
    [-32767] -> [-32767]
    [-32768] -> [-32768]
    

    These functions should be relatively small in size since they're targeted to specific needs rather than the far more general printf family.

提交回复
热议问题