nabulke
nabulke

Reputation: 11255

Converting std::string to boost::posix_time::ptime

The following code converts a std::string to a boost::posix_time::ptime.

After profiling I saw that most of the time spent in that function (about 90%) is wasted with the allocation of the memory for the time_input_facet. I have to admit that I don't fully understand the following code, and specially why the time_input_facet has to be allocated on the 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 allocation?

Upvotes: 3

Views: 3122

Answers (1)

Vladimir Sinenko
Vladimir Sinenko

Reputation: 4667

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

Upvotes: 2

Related Questions