Xig*_*gma 5 c++ optimization stringstream
我的情况如下:
例如,假设我有以下二进制文件内容:
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();
Run Code Online (Sandbox Code Playgroud)
上述方法按预期工作,但是,对于大文件来说,它非常慢,据我所知;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;
}
Run Code Online (Sandbox Code Playgroud)
它附加到预先分配的字符串以最小化复制并避免重新分配。
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |