【问题标题】:Python Threading Performance vs. Number of cores [duplicate]Python线程性能与内核数量[重复]
【发布时间】:2016-05-23 07:26:34
【问题描述】:

我是 python 新手,我正在学习线程和 GIL。 这些是lscpu 命令的统计信息:

 Architecture:          x86_64
 CPU op-mode(s):        32-bit, 64-bit
 Byte Order:            Little Endian
 CPU(s):                4
 On-line CPU(s) list:   0-3
 Thread(s) per core:    2
 Core(s) per socket:    2
 Socket(s):             1
 NUMA node(s):          1
 Vendor ID:             GenuineIntel
 CPU family:            6
 Model:                 69
 Stepping:              1
 CPU MHz:               1700.062
 BogoMIPS:              4789.05
 Virtualization:        VT-x
 L1d cache:             32K
 L1i cache:             32K
 L2 cache:              256K
 L3 cache:              3072K
 NUMA node0 CPU(s):     0-3

当我运行这个简单的 python 线程示例时,我得到以下输出。

import time
import threading

def counter(n):
    for i in range(0,n):
        i = i+1
    return

t1 = threading.Thread(target=counter, args = (10000000,))
t2 = threading.Thread(target=counter, args = (10000000,))

t0 = time.clock()
t1.start()
t2.start()
t1.join()
t2.join()
t3 = time.clock()

print "Total time : %s"%str(t3-t0)

bash@bash:~/Desktop$ python threads.py
Total time : 2.115326

但是当我禁用 3 个核心并重新运行代码时:

bash@bash:~/Desktop$ python threads.py
Total time : 1.115442

这些数字或多或少保持不变。为什么会这样??有人解释。提前谢谢...

【问题讨论】:

    标签: python python-multithreading gil


    【解决方案1】:

    您使用的线程库实际上并没有同时利用多个内核进行计算。

    尝试使用multiprocessing 模块代替计算线程,您应该会看到更多“预期”的结果。

    【讨论】:

    • 并牢记动态频率缩放(TurboBoost 等)之类的事情
    • multiprocessing 不使用线程,它是一个支持生成进程的包[原文如此],不太一样。
    • 感谢您的回复,但我想知道为什么当活动核心数更多时它会变慢
    猜你喜欢
    • 2015-01-22
    • 1970-01-01
    • 2015-04-14
    • 2013-07-15
    • 1970-01-01
    • 2014-02-17
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多