Python多进程只使用一个核心

14 投票
4 回答
19095 浏览
提问于 2025-04-16 22:41

我正在尝试使用来自标准Python文档的代码片段,想学习如何使用多进程模块。代码在这条消息的最后。

我在一台四核机器上使用Python 2.7.1,系统是Ubuntu 11.04(根据系统监视器显示,由于超线程,我的机器实际上有八个核心)。

问题是:所有的工作负载似乎都被安排到一个核心上,这个核心的使用率接近100%。尽管启动了多个进程,但工作负载从来没有在各个核心之间分配。有时工作负载会迁移到另一个核心,但整体上还是没有做到均匀分配。

有没有人知道这是为什么呢?

最好的祝福,

保罗

#
# Simple example which uses a pool of workers to carry out some tasks.
#
# Notice that the results will probably not come out of the output
# queue in the same in the same order as the corresponding tasks were
# put on the input queue.  If it is important to get the results back
# in the original order then consider using `Pool.map()` or
# `Pool.imap()` (which will save on the amount of code needed anyway).
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#

import time
import random

from multiprocessing import Process, Queue, current_process, freeze_support

#
# Function run by worker processes
#

def worker(input, output):
    for func, args in iter(input.get, 'STOP'):
        result = calculate(func, args)
        output.put(result)

#
# Function used to calculate result
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % \
        (current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def mul(a, b):
    time.sleep(0.5*random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5*random.random())
    return a + b


def test():
    NUMBER_OF_PROCESSES = 4
    TASKS1 = [(mul, (i, 7)) for i in range(500)]
    TASKS2 = [(plus, (i, 8)) for i in range(250)]

    # Create queues
    task_queue = Queue()
    done_queue = Queue()

    # Submit tasks
    for task in TASKS1:
        task_queue.put(task)

    # Start worker processes
    for i in range(NUMBER_OF_PROCESSES):
        Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results
    print 'Unordered results:'
    for i in range(len(TASKS1)):
       print '\t', done_queue.get()

    # Add more tasks using `put()`
    for task in TASKS2:
        task_queue.put(task)

    # Get and print some more results
    for i in range(len(TASKS2)):
        print '\t', done_queue.get()

    # Tell child processes to stop
    for i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')

test()

4 个回答

0

多进程并不意味着你会使用处理器的所有核心。你只是得到了多个进程,而不是多核心的进程。这个多核心的使用是由操作系统来管理的,具体情况是不确定的。@Devraj 在评论中提到的问题有一些答案可以帮助你实现你想要的效果。

2

不知道怎么回事,CPU的亲和性被改变了。我之前在使用numpy的时候也遇到过这个问题。我在这里找到了解决办法 http://bugs.python.org/issue17038#msg180663

3

试着把 time.sleep 替换成一些真正需要 CPU 处理的任务,你会发现 multiprocess 运行得很好!比如:

def mul(a, b):
    for i in xrange(100000):
        j = i**2
    return a * b

def plus(a, b):
    for i in xrange(100000):
        j = i**2
    return a + b

撰写回答