我正在尝试使用 multiprocessing
模块在 Python 中编写并行代码,我想知道一种在本地知道哪个 CPU 正在计算的方法,但我只知道 multiprocessing.CPU_count()
了解 CPU 内核总数。
我正在寻找等同于:
omp_get_thread_num()
在 C++ openMP 中。
Python.multiprocessing中有这样的方法吗?
最佳答案
检索进程正在运行的 CPU 并非易事(如果可能的话),但如果您:
根据
multiprocessing.CPU_count()
的报告,启动与可用 CPU 数量相同的进程;假设每个进程将在不同的 CPU 内核中运行,正如使用
multiprocessing
模块时所预期的那样;
然后您可以“作弊”并为每个进程指定一个唯一的名称,以识别其 CPU 核心! :)
for i in xrange(multiprocessing.CPU_count()):
mp = multiprocessing.Process(target=foo, args=(bar,), name=i).start()
然后在子进程中生成的辅助函数中检索它:
print "I'm running on CPU #%s" % multiprocessing.current_process().name
multiprocessing.current_process().name
The process’s name.
The name is a string used for identification purposes only. It has no semantics.
Multiple processes may be given the same name.
The initial name is set by the constructor.
关于Python 多处理 : knowing the thread/CPU number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26715053/