C STD :: Stringstream操作优化

C++ std::stringstream operations optimizations

本文关键字:优化 操作 Stringstream STD      更新时间:2023-10-16

我的情况如下:

  1. 我有一个二进制文件,我正在使用std :: fstream读取操作为(char*)
  2. 我的目标是从文件中获取所有字节,格式化的十六进制,然后将其附加到字符串变量
  3. 字符串变量应按照第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;
}

它附加到预先分配的字符串上,以最大程度地减少复制并避免重新分离。