3 ms·
It's been a long time since I've done C++. I wonder if int x; cout << x; ought to be faster than printf("%d", x), by virtue of knowing the types ahead
by ghettoimp 8y ago
It's been a long time since I've done C++. I wonder if
int x;
cout << x;
ought to be faster than printf("%d", x), by virtue of knowing the types ahead of time?
- octo_t 8y agoIf it weren't for locales, probably yes ;P
- smitherfield 8y agoYes, but only if you first call ios::sync_with_stdio(false); https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdi...
- Someone 8y agoPedantic: No. If you write #include “studio.h” int x; printf(“%d”, x); the compiler knows the types ahead of time, too, so that cannot explain any speed difference (and yes, C compilers do try to avoid the generic printf in the library. See http://www.ciselant.de/projects/gcc_printf/gcc_printf.html http://www.ciselant.de/projects/gcc_printf/gcc_printf.html for examples) (The #include is essential. With it, the compiler can know what printf does, and, in theory, optimize it to a int-to-string conversion and a puts system call. Without it, it cannot, because it doesn’t know what the printf function does (in this case, it is easier to generate fast code for the compiler if it doesn’t have the source available than when it would see source code for a function called printf) Utterly pedantic: no. As given, both are undefined behavior, and it is trivial for a compiler to discover that.
- tom_mellior 8y ago> and yes, C compilers do try to avoid the generic printf in the library That is true for certain format strings (containing only %s or %c conversions), but for %d GCC and Clang don't seem to want to call a print_int function, possibly because there is none: https://gcc.godbolt.org/z/rltFse https://gcc.godbolt.org/z/rltFse