将std :: string转换为boost :: posix_time :: ptime

时间:2012-05-24 06:50:01

标签: c++ boost

以下代码将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;
}

你认为有什么方法可以摆脱这种分配吗?

1 个答案:

答案 0 :(得分:2)

使input_facet在函数内部保持静态:

static time_input_facet *input_facet = new time_input_facet();

这将仅在第一个函数调用上构造构面,并将重用构面。我相信facet允许对同一个对象进行多次后续调用。

更新:您也不需要构建stringstream和locale。只需在单独的函数中或在静态初始化中执行一次,然后使用流。

Updated2:

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;
}
相关问题