Convert std :: string to raise :: posix_time :: ptime

The following code converts a std::stringto boost::posix_time::ptime.

After profiling, I saw that most of the time spent on this function (about 90%) is spent on allocating memory for time_input_facet. I must admit that I do not quite understand the following code, and specifically why it time_input_facetshould be allocated in free memory.

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;
}

Do you see any way to get rid of the selection?

+3
source share
1 answer

Make static_ input_file in function:

static time_input_facet *input_facet = new time_input_facet();

This will build the face only on the first call to the function and will reuse the face. I believe that a facet allows several consecutive calls of the same object.

: . , , , .

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;
}
+2

All Articles