Boostのlexical_castは適度に高速である必要があります。
編集:
詳しく説明させてください。その使用例を次に示します。
std::string strSeconds = lexical_cast<std::string>(time.tv_sec);
std::string strMicroSec = lexical_cast<std::string>(time.tv_usec);
より複雑な文字列フォーマットについては、Boostのドキュメントで基本的なを推奨していstd::stringstream
ます。何かのようなもの:
std::stringstream ss;
ss << time.tv_sec << " seconds, " << (time.tv_usec/1000L) << " milliseconds";
return ss.str();
適度に速く、読みやすく、安全で標準的です。sprintf
cstdioヘッダーからを使用すると、もう少し速度を上げることができる場合があります。(可能な場合はsprintf_sが望ましい)long
printfの変数は明示的にサポートされていませんが、最近の32ビット以上のマシンでは通常同じサイズであるため、%d
指定子を使用して変数を処理できます。
std::string tvtostr(timeval time) {
// unless corrupted, the number of microseconds is always less than 1 second
assert(time.tv_sec >= 0 && time.tv_usec >= 0 && time.tv_usec < 1000000000L);
static_assert(sizeof(long)==4 && sizeof(int)==sizeof(long),
"assuming 32 bit ints and longs" );
// space for one unbounded positive long, one long from 0 to 999,
// the string literal below, and a '\0' string terminator
boost::array<CHAR, 10+3+23+1> buffer;
sprintf_s(buffer.data(), buffer.size(), "%d seconds, %d milliseconds",
time.tv_sec, (time.tv_usec/1000L) );
return buffer.data();
}