简体   繁体   中英

printf performance: Better to use “%d” or “%c” for single digit numbers

I am printing information about a struct which only contains information which will all be a single digit (small indices and char which act as bools mostly).

I want my printf calls to be as efficient as possible. So would it be better to use the normal %i / %d format specifiers, or is it better to use %c and add 0x30 ( '0' ) to the number, since then there shouldn't need to be any formatting for printf to do?

Edit/Clarification: I have profiled some small programs which try both techniques, and the %c can be faster. If this were for production code, I would just stick to the %d , but this is specifically for speed-based competitions. (sorry because that wasn't clear before).

The only way to know for sure is to code up both versions and profile them (or compare the generated machine code). Having said that, I doubt you'd see much difference in runtime performance. Modern compilers are smart, and standard library implementations are tuned to be as efficient as possible. It's quite likely that your printf implementation already has special case handling for single-digit integers that does something similar to what you are proposing. And all of that's down in the noise compared to the overhead of just calling printf in the first place.

Code should be, in order of importance:

  1. Correct - it does everything it is supposed to do, and nothing it isn't supposed to do;
  2. Robust - it shouldn't fall over and die if somebody looks at it funny;
  3. Secure - it's not a malware vector, it doesn't expose any data it shouldn't;
  4. Maintainable - some poor schmuck is eventually going to have to change this code to add functionality (or fix a defect);
  5. Efficient - it shouldn't take any more space or time than necessary to accomplish a given task, which is often driven by choice of algorithm and data structures more than anything specific micro-optimization.

I'd argue that your approach makes your code less maintainable, because it's a non-obvious way to achieve a given result.

Since you are printing integer numbers, use %d , which improves readability.

Using the one over the other won't affect performance in any significant way.

If your application's bottleneck is really the printing phase, then considering using another approach than printf() . Some ideas: use fwrite() , optimize stdout , or POSIX write() , as @YoYoYonnY suggested.

In general, printing in stdout is relatively slow, in comparison to doing computations, for example...

HyperTip: Premature optimization is the root of evil - D. Knuth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM