Python多处理:了解线程/ CPU编号

Lea*_*ess 2 python multithreading multiprocessing

我正在尝试使用multiprocessing模块在Python中编写并行代码,我想知道一种在本地知道哪个CPU正在计算的方法,但我只知道multiprocessing.CPU_count()知道总CPU内核.

我正在寻找相当于:

omp_get_thread_num()
Run Code Online (Sandbox Code Playgroud)

在C++中使用openMP.

Python.multiprocessing中有这样的方法吗?

Mes*_*ion 7

检索进程正在运行的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()
Run Code Online (Sandbox Code Playgroud)

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

print "I'm running on CPU #%s" % multiprocessing.current_process().name
Run Code Online (Sandbox Code Playgroud)

官方文档:

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.
Run Code Online (Sandbox Code Playgroud)