3

以下代码将 a 转换std::string为 a 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;
}

你有什么办法摆脱分配吗?

4

1 回答 1

2

Make the input_facet static inside the function:

static time_input_facet *input_facet = new time_input_facet();

This will construct the facet only on the first function call and will reuse the facet. I believe that the facet allows multiple consequent calls on the same object.

Updated: you also don't need to construct both the stringstream and locale. Just do it once either in a separate function or here in the static initialization, and use the stream consequently.

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;
}
于 2012-05-24T07:09:43.197 回答