Python多处理:了解线程/CPU数量

2024-06-17 15:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我在找一个等价物:

omp_get_thread_num()
< C++ OpenMP中的P>

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


Tags: 模块方法代码getcountcpumultiprocessing内核
1条回答
网友
1楼 · 发布于 2024-06-17 15:04:07

检索进程运行在哪个CPU上(如果可能的话)并不容易,但是如果您:

  • multiprocessing.CPU_count()所报告的,启动与可用CPU相同数量的进程,就像大多数应用程序所做的那样;

  • 假设在使用multiprocessing模块时,每个进程都将在不同的CPU内核中运行;

然后你可以“欺骗”并给每个进程一个唯一的名称来标识它的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

official documentation

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.

相关问题 更多 >