[英]Difference between multiprocessing.cpu_count and os.cpu_count
os
和multiprocessing
模块都定义了一个cpu_count
函数。
os.cpu_count
记录如下:
返回系统中的CPU数量。 如果不确定,则返回None。
和multiprocessing.cpu_count
的文档说:
返回系统中的CPU数量。 可能会引发NotImplementedError。 另请参见os.cpu_count()
在我的机器上,它们都返回相同的结果:
>>> import os
>>> import multiprocessing as mp
>>> os.cpu_count()
8
>>> mp.cpu_count()
8
我本以为multiprocessing.cpu_count
只是对os.cpu_count
引用,但事实并非如此:
>>> os.cpu_count is mp.cpu_count
False
那么它们之间有什么区别呢? 我是否保证他们将始终返回相同的结果? 此外,如果我想指定要为multiprocessing.Pool
创建的多个进程,是否应该使用os
或multiprocessing
的功能?
答案在于multiprocessing.context
,它对BaseContext.cpu_count
定义如下:
# cpython/Lib/multiprocessing/context.py
class BaseContext(object):
def cpu_count(self):
'''Returns the number of CPUs in the system'''
num = os.cpu_count()
if num is None:
raise NotImplementedError('cannot determine number of cpus')
else:
return num
然后,通过multiprocessing
公开此cpu_count
方法:
# cpython/Lib/multiprocessing/__init__.py
__all__ = [x for x in dir(context._default_context) if not x.startswith('_')]
globals().update((name, getattr(context._default_context, name)) for name in __all__)
因此,最后, multiprocessing.cpu_count
只是os.cpu_count
的包装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.