C STD :: Stringstream操作优化
C++ std::stringstream operations optimizations
我的情况如下:
- 我有一个二进制文件,我正在使用std :: fstream读取操作为(char*)
- 我的目标是从文件中获取所有字节,格式化的十六进制,然后将其附加到字符串变量
- 字符串变量应按照第2项的格式保存文件的全部内容。
例如,假设我有以下二进制文件内容:
D0 46 98 57 A0 24 99 56 A3
我要格式化每个字节的方式如下:
stringstream fin;;
for (size_t i = 0; i < fileb_size; ++i)
{
fin << hex << setfill('0') << setw(2) << static_cast<uint16_t>(fileb[i]);
}
// this would yield the output "D0469857A0249956A3"
return fin.str();
上面的方法可以按预期工作,但是,对于大型文件而言,它非常慢,我知道。StringStream是用于输入格式的!
我的问题是,是否有方法可以优化此类代码或我正在一起采用的方法?我唯一的约束是输出应为字符串格式,如上所示。
谢谢。
std::stringstream
相当慢。它不会预先放置,并且总是涉及复制字符串,至少一次以检索其。此外,可以将转换为十六进制的速度更快。
我认为这样的事情可能更具性能:
// Quick and dirty
char to_hex(unsigned char nibble)
{
assert(nibble < 16);
if(nibble < 10)
return char('0' + nibble);
return char('A' + nibble - 10);
}
std::string to_hex(std::string const& filename)
{
// open file at end
std::ifstream ifs(filename, std::ios::binary|std::ios::ate);
// calculate file size and move to beginning
auto end = ifs.tellg();
ifs.seekg(0, std::ios::beg);
auto beg = ifs.tellg();
// preallocate the string
std::string out;
out.reserve((end - beg) * 2);
char buf[2048]; // larger = faster (within limits)
while(ifs.read(buf, sizeof(buf)) || ifs.gcount())
{
for(std::streamsize i = 0; i < ifs.gcount(); ++i)
{
out += to_hex(static_cast<unsigned char>(buf[i]) >> 4); // top nibble
out += to_hex(static_cast<unsigned char>(buf[i]) & 0b1111); // bottom nibble
}
}
return out;
}
它附加到预先分配的字符串上,以最大程度地减少复制并避免重新分离。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 空基优化子对象的地址
- 重载操作程序时出错>>用于类中的字符串 memebr
- 关闭||运算符优化
- 如果 RMW 操作没有任何变化,是否可以针对所有内存顺序对其进行优化
- 使用位操作优化检查
- 按位不操作的编译器优化
- C STD :: Stringstream操作优化
- 为什么这个无操作循环没有优化掉?
- 优化 QScriptEngine 重复操作
- 我如何在数值求解器中优化大量的副本和访问操作
- 如何优化C 对象I/O操作的性能
- 如何优化此数学操作以换取速度
- 如何避免编译器优化某些操作
- 用于获得NOT值的优化位操作
- 优化字节操作CUDA
- 优化块位操作:以4为基数的数字
- 在c++中,如果返回一个指针并立即解引用,这两个操作会被优化掉吗?
- 优化bitset操作
- 为什么volatile局部变量的优化与volatile自变量不同,以及为什么优化器会从后者生成无操作循环