【问题标题】:Alternative to Python Multiprocessing Manager dict for large read only store用于大型只读存储的 Python Multiprocessing Manager dict 的替代方案
【发布时间】:2013-10-02 07:58:46
【问题描述】:

我正在使用 Multiprocessing 和进程使用的大型 (~5G) 只读字典。我首先将整个 dict 传递给每个进程,但遇到内存限制,因此改为使用 Multiprocessing Manager dict(阅读此 How to share a dictionary between multiple processes in python without locking 后)

自更改以来,性能下降了。更快的共享数据存储有哪些替代方案? dict有一个40个字符的字符串key,和2个小字符串元素元组数据。

【问题讨论】:

  • 发现我可以简单地将字典作为一个全局的,并使用线程而不是多处理。看起来很简单,不确定我是否遗漏了什么 - 它似乎有效
  • 很抱歉启动了这个旧线程 - 线程和多处理是两个完全不同的东西。线程不会启动新进程并允许多核执行,与多处理相反,它允许您启动新进程并在多个内核上并行计算。 - 对于小型项目来说,完全避免多处理可能会更快,因为启动此方法可能会比正常处理串行数据涉及更大的性能损失。

标签: python multiprocessing


【解决方案1】:

使用内存映射文件。虽然这可能听起来很疯狂(性能方面),但如果你使用一些巧妙的技巧可能不会:

  1. 对键进行排序,以便您可以在文件中使用二进制搜索来定位记录
  2. 尽量使文件的每一行长度相同(“定宽记录”)

如果您不能使用固定宽度的记录,请使用以下伪代码:

Read 1KB in the middle (or enough to be sure the longest line fits *twice*)
Find the first new line character
Find the next new line character
Get a line as a substring between the two positions
Check the key (first 40 bytes)
If the key is too big, repeat with a 1KB block in the first half of the search range, else in the upper half of the search range

如果性能不够好,请考虑用 C 编写扩展。

【讨论】:

  • 嗯,谢谢,但这对我来说听起来比“if x in mydic”要多得多。有人建议改用线程和全局,所以会看看。
  • 好吧,第一步将是找出它为什么慢。问题是进程启动时间、dict的共享、dict的访问吗?
  • 再次感谢,但我认为您假设我有很多空闲时间来研究 python 标准模块的内部工作原理:) 发现全局和线程而不是多处理工作
  • 如何使用one of the profilers 让Python 告诉您它大部分时间都花在了哪里? :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 2014-01-30
  • 1970-01-01
  • 2013-11-24
相关资源
最近更新 更多