fstream - What is the best way (performance driven) to convert and write variables to a file in c++? -


i want write file:

0x050 addik r13, r0, 4496 0x054 addik r2, r0, 2224 0x058 addik r1, r0, 7536 0x05c brlid r15, 200 ... 

and on... program instruction trace have thousands of lines.

i reading 'elf' decoding instruction, creating object, setting address, instruction, name , registers parameters , writing in above format file.

what best way, measuring in speed/performance, this?

now have (still hexadecimals) , don't know if best way continue writing code:

converting function:

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(); }; 

and writing:

while((newinstruction = manager->newinstruction())){     stream  << utils::tohex(newinstruction->getaddress())             << " "             << utils::tohex(newinstruction->getinstruction())             << endl;     trace->writefile(stream.str());     stream.str(std::string()); } 

edit:

so have reached faster solution based on answers.

for 1 implemented solution given escualo stop creating objects each time read new instruction.

and read answer given thomas matthews , gave me idea not write file @ every instruction read, stringstream works buffer size 1024, , when surpasses value writes stream file:

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());     } } 

for one, avoid creating , destroying std::stringstream every call formatting function.

recall i/o manipulators nothing functions return stream itself. example, manipulator doing indicated above, without resorting temporary std::stringstream like:

#include <iostream> #include <iomanip>  template<typename t,          typename chart,          typename traits = std::char_traits<chart> > inline std::basic_ostream<chart, traits>& myhex(std::basic_ostream<chart, traits>& os) {   return os << "0x"             << std::setfill('0')             << std::setw(2 * sizeof(t))             << std::hex; }  int main() {   int x;   std::cout << myhex<int> << &x << std::endl; } 

to print (for example):

0x0x7fff5926cf9c 

to clarify: not know why choose fill, width, prefix, , format; showing how create i/o manipulator not entail creating , destroying temporary objects.

notice manipulator work std::basic_ostream<chart, traits> such std::cout, std::cerr, std::ofstream, , std::stringstream.


Comments