[SOLVED] Print out bitset quickly in c++

Issue

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.

Solution

The problem is that cin and cout try to synchronize themselves with the library’s stdio buffers. That’s why they are generally slowe
you can turn of 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.

Answered By – Mina Ashraf

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *