c++ - 将 std::string 转换为 boost::posix_time::ptime

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

你有没有办法摆脱分配?

最佳答案

在函数内部使 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/

相关文章:

java - JNI_CreateJavaVM() 每次我运行我的应用程序时都会失败(确切地说)

c++ - 从 Python 调用 IB API

c++ - 使用 boost::range 在 C++ 中进行花式索引

c++ - 如果 std::max() 通过引用返回(必须如此),这可能会导致悬空引用吗?

c++ - 芯片的数据表没有说明如何与之通信

C++在链表中设置下一个节点指针

c++ - OpenGL 程序适用于 AMD 但不适用于 NVIDIA

c++ - 如何将boost线程与Xcode链接起来

c++ - boost::geometry::read_wkt 替代方案?

c++ - 使用相同的 Boost.Asio io_service 同步接受 tcp 连接并作为线程池