3 ms·
Possible trap: Some compilers may recognize the '1' literal used in printf1.c, fold it in to the string, and avoid printf() in both cases. If that happens to yo
by userbinator 9y ago
Possible trap: Some compilers may recognize the '1' literal used in printf1.c, fold it in to the string, and avoid printf() in both cases. If that happens to you, substitute an expression that must be evaluated.
Or more "robustly", an expression that comes from external input (such as getchar()). Compilers can be smart enough to evaluate expressions which are constant.
This reminds me, I briefly played around with JIT'ing printf() itself --- if you look at it the right way, it's basically a "bytecode" interpreter for the format string. I did get some pretty good performance gains, but it turned out simpler for the project it was intended to go in to just switch to a binary protocol instead of text for output.
I also think that writing a (subset of) printf() is a useful exercise for those beginning programming C in general; it's not too difficult (at least if you avoid the floating-point stuff...), but also not too easy either.
- baruch 9y agoNot strictly a JIT but a preprocessor at compile time that makes sprintf calls faster by pre-splitting them: https://github.com/h2o/qrintf https://github.com/h2o/qrintf
- twic 9y agoI recently came across a C++ logging library that parses format strings at compile time using template necromancy: https://blapid.github.io/cpp/2017/10/31/llcpp-a-quest-for-faster-logging-part-2.html https://blapid.github.io/cpp/2017/10/31/llcpp-a-quest-for-fa...
- DerDangDerDang 9y agoThe cool kids are doing it with constexpr. See spdlog and/or fmt
- twic 9y agofmt can check format strings at compile time, but does it generate code to do the formatting? Some quick experiments suggests it will re-parse the format string at runtime to do the formatting.
- dangets 9y agoF# has statically type checked printf also. I know it's a completely different realm than C++, but still pretty interesting. https://fsharpforfunandprofit.com/posts/printf/ https://fsharpforfunandprofit.com/posts/printf/