相关疑难解决方法(0)

Python中的线程效率如何?

我听说Python中的线程效率不高(与其他语言相比).

这是真的?如果是这样,Python程序员如何克服这个问题呢?

python multithreading

11
推荐指数
3
解决办法
4884
查看次数

concurrent.futures.ThreadPoolExecutor.map比for循环慢

我正在使用concurrent.futures.ThreadPoolExecutor来查看我是否可以从我的四核处理器(具有8个逻辑核心)中挤出更多工作.所以我写了下面的代码:

from concurrent import futures

def square(n):
    return n**2

def threadWorker(t):
    n, d = t
    if n not in d:
        d[n] = square(n)

def master(n, numthreads):
    d = {}
    with futures.ThreadPoolExecutor(max_workers=numthreads) as e:
        for i in e.map(threadWorker, ((i, d) for i in range(n))):
            pass  # done so that it actually fetches each result. threadWorker has its own side-effects on d
    return len(d)

if __name__ == "__main__":
    print('starting')
    print(master(10**6, 6))
    print('done')
Run Code Online (Sandbox Code Playgroud)

有趣的是,在for循环中编写相同的功能需要大约一秒钟:

>>> d = {}
>>> for i in range(10**6): …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-3.x threadpoolexecutor concurrent.futures

6
推荐指数
1
解决办法
4499
查看次数