python多处理库顶部类似于thin mapreduce的层。
mr4mp的Python项目详细描述
python多处理库顶部类似于thin mapreduce的层。
软件包安装和使用
PYPI上提供该软件包:
python -m pip install mr4mp
库可以按通常的方式导入:
import mr4mp
示例
word文档索引
假设我们有一些函数可以用来建立随机生成单词的索引:
def word(): # Generate a random 7-letter "word". return ''.join(choice(ascii_lowercase) for _ in range(7)) def index(id): # Build an index mapping some random words to an identifier. return {w:{id} for w in {word() for _ in range(100)}} def merge(i, j): # Merge two index dictionaries i and j. return {k:(i.get(k,set()) | j.get(k,set())) for k in i.keys() | j.keys()}
然后,我们可以按以下方式构造索引:
start = timer() pool = mr4mp.pool() pool.mapreduce(index, merge, range(100)) print("Finished in " + str(timer()-start) + "s using " + str(len(pool)) + " process(es).")
以上可能会产生以下输出:
Finished in 0.664681524217187s using 2 process(es).
假设我们已明确指定只能使用一个进程:
pool = mr4mp.pool(1)
在上述修改之后,我们可能会看到代码块的以下输出:
Finished in 2.23329004518571s using 1 process(es).