On what CPU cores are my Python processes running?

前端 未结 3 1052
臣服心动
臣服心动 2020-12-14 14:36

The setup

I have written a pretty complex piece of software in Python (on a Windows PC). My software starts basically two Python interpreter shells.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 15:02

    1, 2: You have three real threads, but in CPython they're limited by GIL , so, assuming they're running pure python, code you'll see CPU usage as if only one core used.

    3: As said gdlmx it's up to OS to choose a core to run a thread on, but if you really need control, you can set process or thread affinity using native API via ctypes. Since you are on Windows, it would be like this:

    # This will run your subprocess on core#0 only
    p = subprocess.Popen(['python', mySubprocessPath], shell = True)
    cpu_mask = 1
    ctypes.windll.kernel32.SetProcessAffinityMask(p._handle, cpu_mask)
    

    I use here private Popen._handle for simplicty. The clean way would beOpenProcess(p.tid) etc.

    And yes, subprocess runs python like everything else in another new process.

提交回复
热议问题