我想把这样的东西写到一个文件中:
0x050 addik r13, r0, 4496
0x054 addik r2, r0, 2224
0x058 addik r1, r0, 7536
0x05c brlid r15, 200
...
等等...它是一个程序指令跟踪,将有数千行。
我正在从一个“小 Sprite ”中读取解码指令,创建一个对象,设置它的地址、指令、名称和寄存器参数,然后以上述格式将其写入文件。
衡量速度/性能的最佳方法是什么?
现在我有了这个(仍然只是十六进制),我不知道这是否是继续编写我的代码的最佳方式:
转换函数:
static std::string toHex(const T &i) {
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
};
和写作:
while((newInstruction = manager->newInstruction())){
stream << Utils::toHex(newInstruction->getAddress())
<< " "
<< Utils::toHex(newInstruction->getInstruction())
<< endl;
trace->writeFile(stream.str());
stream.str(std::string());
}
编辑:
所以我根据答案得出了一个更快的解决方案。
我实现了 Escualo 给出的解决方案。每次阅读新指令时停止创建对象。
然后我阅读了 Thomas Matthews 给出的答案并让我想到不要在每次读取指令时都写入我的文件,因此字符串流现在像大小为 1024 的缓冲区一样工作,当它超过该值时,然后将流写入文件:
while((newInstruction = manager->newInstruction())){
stream << myHex<unsigned int> << newInstruction->getAddress() << ' '
<< myHex<uint32_t> << newInstruction->getInstruction();
if(stream.tellp() > 1024){
trace->writeFile(stream.str());
stream.str(std::string());
}
}
最佳答案
由于文件 I/O 比格式化时间慢,我建议格式化到缓冲区, block 将缓冲区写入文件。
char text_buffer[1024];
unsigned int bytes_formatted = 0;
for (unsigned int i = 0; i < 10; ++i)
{
int chars_formatted = snprintf(&text_buffer[bytes_formatted],
1024-bytes_formatted,
"hello %d", i);
if (chars_formatted > 0)
{
bytes_formatted += chars_formatted;
}
}
my_file.write(text_buffer, bytes_formatted);
大多数文件 I/O 操作的开销都是恒定的,与操作无关。所以一次操作可以写入的数据越多越好。
关于c++ - 在 C++ 中将变量转换和写入文件的最佳方式(性能驱动)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347134/