简体   繁体   English

为Python程序分配多个内核

[英]Assigning Multiple Cores to a Python Program

I notice when I run my heavily CPU dependant python programs, it only uses a single core. 我注意到当我运行高度依赖CPU的python程序时,它仅使用一个内核。 Is it possible to assign multiple cores to the program when I run it? 运行该程序时是否可以为其分配多个内核?

You have to program explicitly for multiple cores. 您必须为多个内核进行显式编程。 See the Symmetric Multiprocessing options on this page for the many parallel processing solutions in Python. 有关Python中许多并行处理解决方案的信息,请参阅此页面上的“对称多处理”选项。 Parallel Python is a good choice if you can't be bothered to compare the options, look at the examples here . 如果您不愿意比较这些选项,那么并行Python是一个不错的选择,请查看此处的示例。

Some problems can't take advantage of multiple cores though. 但是,有些问题不能利用多核。 Think about how you could possibly run up the stairs faster with the help of three friends. 考虑一下如何在三个朋友的帮助下更快地上楼梯。 Not going to happen! 不会发生!

如果您的问题的任何部分都可以并行运行,则应查看多处理模块

I wonder why nobody mentioned CPython's GIL (Global Interpreter Lock) yet. 我想知道为什么还没有人提到CPython的GIL(全局解释器锁)。 It basically means that multiple threads inside one Python interpreter cannot use the power of multiple cores because many operations are protected by a global lock in order to be thread-safe. 从根本上讲,这意味着一个Python解释器中的多个线程无法使用多个内核的功能,因为许多操作均受全局锁保护以确保线程安全。 This only applies to a small amount of applications - the CPU-bound ones. 这仅适用于少量应用程序-受CPU限制的应用程序。 For more info, just search for the term "GIL", there are already many questions on it (like that one , for example). 有关更多信息,只需搜索术语“ GIL”,就已经有很多问题(例如类似的问题)。

This answer of course assumes that you are in fact using multiple threads, or else you won't be able to use multiple cores anyway ( multiprocessing would be another possibility). 这个答案当然是假设您实际上正在使用多个线程,否则您将无法使用多个内核( 多处理是另一种可能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM