随着进程数量的增加,Python程序的速度变慢。为什么?如何克服?

时间:2018-09-10 14:38:05

标签: python python-3.x performance python-multiprocessing

我有一段愚蠢的代码(blah.py),该代码只是执行一些CPU负载:

if __name__ == "__main__":
    while True:
        startTime = perf_counter()

        primes = []
        for possiblePrime in range(2, 40000):

            # Assume number is prime until shown it is not.
            isPrime = True
            for num in range(2, possiblePrime):
                if possiblePrime % num == 0:
                    isPrime = False
                    break

            if isPrime:
                primes.append(possiblePrime)

        print(f'Took {perf_counter() - startTime}s')

然后我只是同时在多个shell中运行它,例如:cmd python.exe blah.py

我看到执行时间取决于启动的进程数。

proc. #  time
1        8.9s
2        9.6s
4        11.1s
8        17.3s

使用进程池等时出现相同的症状。

系统:Windows 10 64位,CPU i7 4核(8逻辑),8GB RAM,Python 3.6.3 | Anaconda自定义(64位)| (默认值,2017年10月15日,03:27:45)在Win32上的[MSC v.1900 64位(AMD64)]

为什么python程序会以这种方式运行? 可能是某种形式的隐藏的进程间通信发生,或者是我不知道的任何类型的全局锁(真的是GIL吗?),或者可能是针对python环境的奇特的Anaconda设置。

如何克服此类问题?

预先感谢大家的答复。

P.S。在32核服务器上运行一些实际代码时-性能会急剧下降。

0 个答案:

没有答案