> In fact, I have a hard time envisioning any program where the cost of
> printf() is noticeable at all.
I have one. I'm doing data-capture and pre-processing on a relatively slow system (mini-itx, to keep the heat down so as not to cause optical turbulence in the lab). We acquire data at about 1 MHz on 4 channels, and need to do some simple preprocessing (offset and scale) then save to file. The file is a 4-column text-file as asciihex eg "0x1234 0x4567 0x3432 0x6666\n", i.e format string is "0x%x\t0x%x\t0x%x\t0x%x\n". So the printf cost is definitely not negligible, when we call it 1 million times a second.
(Yes, we could optimise further and keep the data in raw binary form, but it's not strictly necessary yet, would prevent us adding headers, and would make for a non-human-friendly file format. But I'd certainly welcome a fast printf for the simple cases)
Posted May 25, 2012 11:13 UTC (Fri) by dgm (subscriber, #49227)
[Link]
The think is, the solution in this case is simply to write your own formating function. It's really simple, much simpler than the kind of optimizations you were asking for.
An example:
char * to_hex(unsigned v){
static char digits[16] = "0123456789ABCDEF";
static char buffer[8]; /* assuming 32 bits */
int i;
for (i = 7; i >= 0; i--) {
buffer[i] = digits[v & 0xF];
v >>= 4;
}
return buffer;
}
GCC Explorer - an interactive take on compilation
Posted May 25, 2012 14:04 UTC (Fri) by jwakely (subscriber, #60262)
[Link]
But do you call printf with compile-time constants a million times a second?
GCC Explorer - an interactive take on compilation
Posted Jul 3, 2012 3:32 UTC (Tue) by Richard_J_Neill (subscriber, #23093)
[Link]
Much more significantly, what about an embedded system. On an Arduino, the runtime and storage costs of printf are severe. (typically ~3% of ROM)
Serial.print ("Clock period is " STRINGIFY(CLOCK_NS) "ns\n");
...which should print: "Clock period is 40 ns\n"
but actually prints: "Clock period is (1000/25 ns\n")
This sort of thing can't be done in the preprocessor and it's too expensive to do at runtime. The only workaround seems to be to actually manually: #define CLOCK_NS_STR "40"
which is a bug just waiting to happen.