要在Python中处理的线程

时间:2016-05-02 09:32:03

标签: python multithreading performance

如何将此代码重写为使用进程以获得更快的Python结果?

from threading import Thread

def test_function(n):
    while n > 0:
        n = n - 1


thread1 = Thread(target=test_function, args=(50000000,))
thread1.start()

thread2 = Thread(target=test_function, args=(50000000,))
thread2.start()

thread1.join()
thread2.join()

该脚本占用了127.84088587760925秒

我试过这样的事情。但它没有用。

from multiprocessing import Process

def test_function(n):
    while n > 0:
        n = n - 1

    t1 = Process(target=test_function, args=(50000000,))
    t1.start()
    t2 = Process(target=test_function, args=(50000000,))
    t2.start()
    t1.join()
    t2.join()

没有线程

def test_function(n):
    while n > 0:
        n = n - 1

count(500000000)
count(500000000)

脚本耗时162.00484490394592

有任何帮助吗?非常感谢

1 个答案:

答案 0 :(得分:1)

由于CPython的global interpreter lock,线程无助于提高CPU绑定计算的性能。一次只能运行一个线程,线程切换成本会使代码比单线程代码慢。

要利用多个核心,请尝试multi-processing module