以下代码将 std::string
转换为 boost::posix_time::ptime
。
分析后,我发现花在该函数上的大部分时间(大约 90%)都浪费在为 time_input_facet
分配内存。我不得不承认我不完全理解下面的代码,特别是为什么 time_input_facet
必须在空闲内存上分配。
using boost::posix_time;
const ptime StringToPtime(const string &zeitstempel, const string &formatstring)
{
stringstream ss;
time_input_facet* input_facet = new time_input_facet();
ss.imbue(locale(ss.getloc(), input_facet));
input_facet->format(formatstring.c_str());
ss.str(zeitstempel);
ptime timestamp;
ss >> timestamp;
return timestamp;
}
你有没有办法摆脱分配?
最佳答案
在函数内部使 input_facet 为静态:
static time_input_facet *input_facet = new time_input_facet();
这将仅在第一次函数调用时构造构面,并将重用该构面。我相信 facet 允许对同一对象进行多次后续调用。
更新:您也不需要同时构造字符串流和语言环境。只需在单独的函数中或在此处的静态初始化中执行一次,然后使用流。
更新2:
const ptime StringToPtime(const string &zeitstempel, const string &formatstring)
{
static stringstream ss;
static time_input_facet *input_facet = NULL;
if (!input_facet)
{
input_facet = new time_input_facet(1);
ss.imbue(locale(locale(), input_facet));
}
input_facet->format(formatstring.c_str());
ss.str(zeitstempel);
ptime timestamp;
ss >> timestamp;
ss.clear();
return timestamp;
}
关于c++ - 将 std::string 转换为 boost::posix_time::ptime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10732518/