Python多进程:如何获取线程/CPU编号
我正在尝试在Python中使用 multiprocessing
模块编写并行代码,我想知道有没有办法在本地知道哪个CPU正在进行计算,但我只知道 multiprocessing.CPU_count()
可以用来获取CPU的总核心数。
我在寻找一个类似于:
omp_get_thread_num()
在C++的openMP中的方法。
在Python的multiprocessing中有这样的功能吗?
1 个回答
7
要知道一个进程正在使用哪个CPU并不简单(有时候甚至不可能),但是如果你:
启动的进程数量和可用的CPU数量一样多,这个数量可以通过
multiprocessing.CPU_count()
来查看,很多应用程序都是这么做的;假设每个进程都会在不同的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.