多线程性能开销

Eri*_*uer 3 python multithreading

所以基本上我创建了这个程序,为redis添加了值.到目前为止我得到了这个时间:

real 0m27.759s
user 0m18.129s
sys  0m5.580s
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行多个线程时:

if __name__ == '__main__':
    try:
        for x in range(0, NUM_THREADS):
            Thread(None, startProgram, None,
                   (NUM_HOSTS/NUM_THREADS*x+1,
                    NUM_HOSTS/NUM_THREADS*(x+1))).start()
    except Exception as errtxt:
        print errtxt
Run Code Online (Sandbox Code Playgroud)

我用NUM_THREADSset ot 得到这个10:

real 0m32.642s
user 0m22.953s
sys  0m11.473s
Run Code Online (Sandbox Code Playgroud)

为什么我的程序运行速度,线程越多

我正在运行Linux Ubuntu 11.04和Python 2.7.1.

phi*_*hag 9

结果取决于Python实现,cpython的GIL防止并行计算比顺序计算更快.

考虑使用multiprocessing模块,它在自己的Python进程中执行每个线程,或者使用替代的无GIL的Python实现,如IronPythonJython.