Python无通信多核

Python无通信多核,python,multiprocessing,recommendation-engine,Python,Multiprocessing,Recommendation Engine,我想调用methode GetRecommensions,它只是将对特定用户的建议pickle到一个文件中。我使用了一本书中的代码。但是我看到只有一个核心可以工作,我希望我的所有核心都能工作,因为这样会快得多 这里是方法 def getRecommendations(prefs,person,similarity=sim_pearson): print "working on recommendation" totals={} simSums={} for oth

我想调用methode GetRecommensions,它只是将对特定用户的建议pickle到一个文件中。我使用了一本书中的代码。但是我看到只有一个核心可以工作,我希望我的所有核心都能工作,因为这样会快得多

这里是方法

def getRecommendations(prefs,person,similarity=sim_pearson):
    print "working on recommendation"
    totals={}
    simSums={}
    for other in prefs:
    # don't compare me to myself
        if other==person: continue
        sim=similarity(prefs,person,other)
        # ignore scores of zero or lower
        if sim<=0: continue
        for item in prefs[other]:
            # only score movies I haven't seen yet
            if item not in prefs[person] or prefs[person][item]==0:
                # Similarity * Score
                totals.setdefault(item,0)
                totals[item]+=prefs[other][item]*sim
                # Sum of similarities
                simSums.setdefault(item,0)
                simSums[item]+=sim
    # Create the normalized list
    rankings=[(total/simSums[item],item) for item,total in totals.items( )]
    # Return the sorted list
    rankings.sort( )
    rankings.reverse( )
    ranking_output = open("data/rankings/"+str(int(person))+".ranking.recommendations","wb")
    pickle.dump(rankings,ranking_output)
    return rankings
正如你所看到的,我试图向每位客户推荐。这将在以后使用

那么我如何对这个方法进行多重处理呢?通过阅读一些示例,甚至是你想要的东西(粗略地说,未经测试),我无法理解:


(这是假设您只将'i'传递给GetRecommensions,因为pickle.load应该只执行一次)

James给出的答案是正确的。我只想补充一点,您需要通过

from multiprocessing import Pool

而且,池(4)意味着您要创建4个“工作”进程,这些进程将并行工作以执行您的任务。

对于什么样的站池=池(4),我必须向批评者提供此方法的建议。因为我想用它来做几件事。阅读Pool的文档肯定会有帮助:)(注意,有许多其他方法可以使用多处理来做你想做的事情。你可能更喜欢imap_无序)我可以用任何方式获取内核的真实数量吗,所以我可以说Pool(numberOfCores-1)?
from multiprocessing import Pool
NUMBER_OF_PROCS = 5 # some number... not necessarily the number of cores due to I/O

pool = Pool(NUMBER_OF_PROCS)

for i in customerID:
    pool.apply_async(getRecommendations, [i])

pool.close()
pool.join()
from multiprocessing import Pool