简体   繁体   English

Python和CPU使用率

[英]Python and CPU usage

I've used Python to write a piece of code that can be very time consuming(contains a lot of recursions). 我使用Python编写了一段非常耗时的代码(包含许多递归)。 I was testing the code's runtime, and I noticed no matter how complicated the code becomes, Python never consumes the full computing power of my CPU. 我正在测试代码的运行时,并且发现无论代码变得多么复杂,Python都不会消耗CPU的全部计算能力。 I'm running Python on Windows7 with Intel Dual Core, and Python never uses more than 1 CPU. 我在具有Intel Dual Core的Windows7上运行Python,而Python从未使用超过1个CPU。 Basically one CPU is running while the other one is on idle. 基本上一个CPU在运行,而另一个在空闲。

Can someone explain a bit of what's happening in the background? 有人可以解释一下后台发生的事情吗? Thanks in advance! 提前致谢!

Your script is running in a single process, so runs on a single processor. 您的脚本在单个进程中运行,因此在单个处理器上运行。 The Windows scheduler will probably move it from one core to another quite frequently, but it can't run a single process in more than one place at a time. Windows调度程序可能会很频繁地将其从一个内核转移到另一个内核,但是它一次不能在一个以上的地方运行一个进程。

If you want to use more of your CPU's grunt, you need to figure out how to split your workload so you can run multiple instances of your code in multiple processes. 如果要使用更多的CPU资源,则需要弄清楚如何分配工作负载,以便可以在多个进程中运行代码的多个实例。

如果您的python应用程序不是多线程的,它将不会使用超过1个cpu内核来执行。

Actually a multi-threaded Python application is not enough to use more than 1 core of your cpu. 实际上,多线程Python应用程序不足以使用cpu的多个内核。 Python uses a construct called the "Global Interpreter Lock" (GIL). Python使用一种称为“全局解释器锁定”(GIL)的构造。 All code within your instance of Python has to obtain this lock, meaning that within your Python application only one thread of code will be executed at any given point in time, even if you have multiple processors and are multi-threading Python实例中的所有代码都必须获得此锁,这意味着在Python应用程序中,即使您有多个处理器并且是多线程的,在任何给定的时间点也只能执行一个代码线程。

That said - if you use the multiprocessing module, you can use more than one core: 就是说-如果您使用多处理模块,则可以使用多个内核:

import multiprocessing

def run():
    x = 1+1
    save(x)

if __name__=="__main__":
    for i in range(100):
        p = multiprocessing.Process(target=run)
        p.start()

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

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