Python中的线程与普通线程

2024-04-28 16:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

import time
import threading
import multiprocessing

def fn():
    '''since all 3 functions were identical you can just use one ...'''
    x = 0
    while  x < 100000000:
        x += 1




def TEST_THREADS():
    new_thread1  = threading.Thread(target = fn , args = ())
    new_thread2  = threading.Thread(target = fn, args = ())
    new_thread1.start()
    new_thread2.start()
    new_thread1.join()
    new_thread2.join()

def TEST_NORMAL():
    fn()
    fn()

def TEST_MULTIPROCESSING():
    new_thread1  = multiprocessing.Process(target = fn , args = ())
    new_thread2  = multiprocessing.Process(target = fn, args = ())
    new_thread1.start()
    new_thread2.start()
    new_thread1.join()
    new_thread2.join()
if __name__ == "__main__":  
    '''It is very important to use name == __main__ guard code with threads         and multiprocessing'''
    import timeit
    print ("Time to Run 1x: %0.2fs"%(timeit.timeit(fn,number=1),))
    print ("NORMAL:%0.2fs"%(timeit.timeit(TEST_NORMAL,number=1),))
    print ("Threaded: %0.2fs"%(timeit.timeit(TEST_THREADS,number=1),))
    print ("Multiprocessing: %0.2fs"%    (timeit.timeit(TEST_MULTIPROCESSING,number=1),))

我发现了关于GIL和线程的有趣演示: http://www.dabeaz.com/python/NewGIL.pdf 所以我写了类似的代码,但是得到了奇怪的结果:

Time to Run 1x: 11.60s
NORMAL:23.15s
Threaded: 23.43s
Multiprocessing: 1.19s

正如您所看到的,线程方法比普通方法运行得更快,或者速度相等(0.28秒不太多)。 我发现了一些文章和类似的问题,但到处都是演示的结果-线程速度较慢。你知道吗

我是做错了什么还是新的Python版本改进了GIL?你知道吗

然而,多处理也变得疯狂,工作速度比其他人快20倍!可以吗?你知道吗


Tags: testimporttargetnewdefargsmultiprocessingstart
1条回答
网友
1楼 · 发布于 2024-04-28 16:25:43

在现代Python中,GIL并不像以前那么糟糕(以前,您可以期望CPU绑定的线程代码运行得有意义地慢),因此您的观察结果与您所期望的大致相同。你知道吗

从个人经验来看,cpython2.7上的一堆CPU绑定线程可以使用接近两个CPU内核,完成的工作不到一个内核的75%。由于它们rewrote the GIL in CPython 3.2,这种开销基本上消失了;您仍然无法从线程中获得任何东西,但最终使用了1-1.1个内核的计算量,并完成了95-100%的内核工作量。基本上,GIL不再有意义地降低代码的速度,但它仍然会阻止您从使用CPU绑定的代码(不是基于第三方GIL发布的扩展,如numpy)中获得好处。你知道吗

相关问题 更多 >