[英]Difference between multiprocessing.cpu_count and os.cpu_count
Both os
and multiprocessing
modules define a cpu_count
function. os
和multiprocessing
模块都定义了一个cpu_count
函数。
os.cpu_count
is documented as follows: os.cpu_count
记录如下:
Return the number of CPUs in the system.
返回系统中的CPU数量。 Returns None if undetermined.
如果不确定,则返回None。
and multiprocessing.cpu_count
's documentation says: 和
multiprocessing.cpu_count
的文档说:
Return the number of CPUs in the system.
返回系统中的CPU数量。 May raise NotImplementedError.
可能会引发NotImplementedError。 See also os.cpu_count()
另请参见os.cpu_count()
On my machine, they both return the same result: 在我的机器上,它们都返回相同的结果:
>>> import os
>>> import multiprocessing as mp
>>> os.cpu_count()
8
>>> mp.cpu_count()
8
I would have thought that multiprocessing.cpu_count
would be a mere reference to os.cpu_count
, but it is not: 我本以为
multiprocessing.cpu_count
只是对os.cpu_count
引用,但事实并非如此:
>>> os.cpu_count is mp.cpu_count
False
So what is the difference between them? 那么它们之间有什么区别呢? Am I guaranteed that they'll always return the same result?
我是否保证他们将始终返回相同的结果? Moreover, if I want to specify a number of processes to create for
multiprocessing.Pool
, should I use os
or multiprocessing
's function? 此外,如果我想指定要为
multiprocessing.Pool
创建的多个进程,是否应该使用os
或multiprocessing
的功能?
The answer lies in multiprocessing.context
, which defines BaseContext.cpu_count
as follows: 答案在于
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
Then, this cpu_count
method is exposed by multiprocessing
: 然后,通过
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__)
So in the end, multiprocessing.cpu_count
is nothing but a wrapper around os.cpu_count
. 因此,最后,
multiprocessing.cpu_count
只是os.cpu_count
的包装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.