Python 多处理 : knowing the thread/CPU number

标签 python multithreading multiprocessing

我正在尝试使用 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

来自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.

关于Python 多处理 : knowing the thread/CPU number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26715053/

相关文章:

c++ - std::list 中无锁的并行追加和迭代

ios - 使用 dispatch_async() 避免 View 阻塞的解决方法是什么

python-2.7 - Python多处理: how to exit cleanly after an error?

python - 如何注册序列中的 ID 和出现次数(或次数)?

python - 无法在azure web应用程序上部署flask应用程序

python - 无法使用自定义小部件更改可检查 QListViewItem 的状态

Python 多处理 : socket error timeout while remote connection to a Manager

python - 使用 Pandas 绘制包含列表的列

java - 如何将 eval 方法中包含的两个文件作为线程运行?

linux - 我如何使用 perf 获取多处理器计算机中的每个 cpu 消息?