'strncpy' vs. 'sprintf'

后端 未结 4 1226
萌比男神i
萌比男神i 2021-01-31 06:01

I can see many sprintf\'s used in my applications for copying a string.

I have a character array:

char myarray[10];
const char *str = \"myst         


        
4条回答
  •  -上瘾入骨i
    2021-01-31 06:29

    The different versions of printf/scanf are incredibly slow functions, for the following reasons:

    • They use variable argument lists, which makes parameter passing more complex. This is done through various obscure macros and pointers. All the arguments have to be parsed in runtime to determine their types, which adds extra overhead code. (VA lists is also quite a redundant feature of the language, and dangerous as well, as it has farweaker typing than plain parameter passing.)

    • They must handle a lot of complex formatting and all different types supported. This adds plenty of overhead to the function as well. Since all type evaluations are done in runtime, the compiler cannot optimize away parts of the function that are never used. So if you only wanted to print integers with printf(), you will get support for float numbers, complex arithmetic, string handling etc etc linked to your program, as complete waste of space.

    • Functions like strcpy() and particularly memcpy() on the other hand, are heavily optimized by the compiler, often implemented in inline assemble for maximum performance.

    Some measurements I once made on barebone 16-bit low-end microcontrollers are included below.

    As a rule of thumb, you should never use stdio.h in any form of production code. It is to be considered as a debugging/testing library. MISRA-C:2004 bans stdio.h in production code.

    EDIT

    Replaced subjective numbers with facts:

    Measurements of strcpy versus sprintf on target Freescale HCS12, compiler Freescale Codewarrior 5.1. Using C90 implementation of sprintf, C99 would be more ineffective yet. All optimizations enabled. The following code was tested:

      const char str[] = "Hello, world";
      char buf[100];
    
      strcpy(buf, str);
      sprintf(buf, "%s", str);
    

    Execution time, including parameter shuffling on/off call stack:

    strcpy   43 instructions
    sprintf  467 instructions
    

    Program/ROM space allocated:

    strcpy   56 bytes
    sprintf  1488 bytes
    

    RAM/stack space allocated:

    strcpy   0 bytes
    sprintf  15 bytes
    

    Number of internal function calls:

    strcpy   0
    sprintf  9
    

    Function call stack depth:

    strcpy   0 (inlined)
    sprintf  3 
    

提交回复
热议问题