ragingcorgi
ragingcorgi

Reputation: 3468

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). 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. I'm running Python on Windows7 with Intel Dual Core, and Python never uses more than 1 CPU. Basically one CPU is running while the other one is on idle.

Can someone explain a bit of what's happening in the background? Thanks in advance!

Upvotes: 3

Views: 3532

Answers (3)

Tristan Reid
Tristan Reid

Reputation: 6154

Actually a multi-threaded Python application is not enough to use more than 1 core of your cpu. Python uses a construct called the "Global Interpreter Lock" (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

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()

Upvotes: 3

D_Bye
D_Bye

Reputation: 899

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.

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.

Upvotes: 6

Colin D
Colin D

Reputation: 5661

If you python application is not multi-threaded it is not going to execute using more than 1 core of your cpu.

Upvotes: 2

Related Questions