Reputation: 182
Im writing a program that outputs binary, and I got alot of it I want to output to the terminal, but this takes along time. In other places in my program where I want to quickly output strings I use
_putchar_nolock
and for floating point and decimal numbers I use
printf
Currently my code looks like this for outputting binary numbers
for (size_t i = 0; i < arraysize; i++)
{
std::cout << (std::bitset<8>(binarynumbers[i]));
}
the output gives a nice 0s and 1s which is what I want, no hex. Issue is when I ran performance benchmarks and testing, I found that std::cout was significantly slower than _putchar_nolock and printf.
Looking online I could not find a way to use printf on a bitset and have it output 0s and 1s. and _putchar_nolock would seem like it would be just as slow having to do all the data conversion.
Does anyone know a fast and efficient way to output a bitset in c++? My program is singlethreaded and simple so I dont have an issue putting unsafe code for performance in there, performance is a big issue in the code right now.
Thanks for any help.
Upvotes: 0
Views: 1419
Reputation: 353
The problem is that cin
and cout
try to synchronize themselves with the library's stdio buffers. That's why they are generally slow;
you can turn this synchronization off and this will make cout
generally much faster.
std::ios_base::sync_with_stdio(false);//use this line
You can also get an std::string
from the bitset using the to_string()
function. You can then use printf
if you want.
Upvotes: 1
Reputation: 65
I wanted to drop comment don't have enough reps. You can use to_string member of bitset class. This probably should work:
std::cout << std::bitset<8>(binarynumbers[i]).to_string();
Upvotes: 0