【问题标题】:How to dump my class(with stl container) out, make it fast to load next time?如何转储我的课程(使用 stl 容器),使其下次快速加载?
【发布时间】:2021-12-20 11:20:51
【问题描述】:

我有一个大型容器类来读取文件并保存一些数据,它看起来像:

class MyData {
 public:
  void Load(const std::vector<string>& file_paths) {  // this is a slow funuction, need to read a lot of files.
     for (const auto & f : file_paths) {
       // read file, and save the data in to stl containers
     }
  }
 private:
  std::vector<double> a;
  std::unordered_map<string, double>b; // there may be more containers.
}

每当我需要使用这个类时,我需要:

MyData mdata;
std::vector<std::string> fs; // thousands of files need to read
mdata.Load(fs); // very slow

但是 Mdata 不经常更新,我可以把它转储出来,并使用转储的类,所以让它更快? 例如:

MyData load_dump(const std::string& dump_file_path) {
  // help needed
}

const MyData& mdata = load_dump("dump.bin"); // load the dumped file, to speed up

你能帮忙吗?

【问题讨论】:

  • 我们不知道 Load() 中的内容,除了它很慢......为什么它很慢?代码是什么样的?即使是格式相对复杂的文件(多流、混合二进制 + xml)通常也会在几毫秒内加载。显示一些代码,没有代码我们无能为力。
  • @MichaëlRoy 好的,谢谢提醒,慢的原因是我需要加载数千个文件,它需要超过 10 秒。
  • 为什么觉得有必要保存mdata,不能只留在内存中?你有资源限制吗?您需要多久刷新一次,重新加载其源文件?
  • @MatG 因为我经常使用它,每次启动程序时,我都会花费 10 秒来加载。我不知道如何让它永久保存在内存中,我想这就是我想要的。

标签: c++ serialization stl


【解决方案1】:

当然可以。对于vector&lt;double&gt;,您可以简单地使用ofstream::write(a.data(), a.size())。对于地图之类的东西,您需要进行某种序列化,因为它们的内部表示更复杂。您可以使用http://www.boost.org/libs/serialization/ 来获得一些通用的解决方案,或者您可以自己编写代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多