我正在编写一个自定义记录器,我将我的日志消息缓冲在 std::stringstream
中并在 std::ofstream
时将其刷新到文件 ( std::stringstream
)足够大(以节省一些 IO 延迟)。自 std::stringstream
没有 .size()
方法,我使用 seekg
和 tellg
:
template <typename T>
MyClass & operator<< (const T& val)
{
boost::unique_lock<boost::mutex> lock(mutexOutput);
output << val; //std::stringstream output;
output.seekg(0, std::ios::end);
if(output.tellg() > 1048576/*1MB*/){
flushLog();
}
return *this;
}
问题:
在我看来,每当我调用此方法时,它都会使用 seekg
开始计算从头到尾的字节数,并使用 tellg
获取大小.我想到这个设计首先是为了节省一些 IO 时间,但是:这种连续计数不是会带来更大的成本吗(如果调用此方法的次数很高并且日志消息很小,就像大多数情况下一样) )?
有更好的方法吗?
还有一个附带问题:是 1MB
当今普通计算机中的缓冲区大小是一个很好的数字吗?
谢谢
最佳答案
您可以只使用ostringstream::tellp()
来获取字符串的长度。这是从 http://en.cppreference.com/w/cpp/io/basic_ostream/tellp 中提取的示例.
#include <iostream>
#include <sstream>
int main()
{
std::ostringstream s;
std::cout << s.tellp() << '\n';
s << 'h';
std::cout << s.tellp() << '\n';
s << "ello, world ";
std::cout << s.tellp() << '\n';
s << 3.14 << '\n';
std::cout << s.tellp() << '\n' << s.str();
}
输出:
0 1 13 18 hello, world 3.14
关于c++ - 如何跟踪 std::stringstream 中的当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24795439/