Python多处理:知道线程/CPU编号



我正试图使用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()

然后在子流程中生成的worker函数中检索它:

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.

最新更新