簡體   English   中英

如何通過python充分利用多核

[英]How to fully take advantage of multi-cores by python

我使用python在Ubuntu上執行此程序

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while True:
      count += 1

# Create two threads as follows
try:
   for index in xrange(1,50000):
     thread.start_new_thread( print_time, ("Thread-" + str(index), 0, ) )

except:
   print "Error: unable to start thread"

while 1:
   pass

我希望所有8個內核的使用率都為100%,但是通過System Monitor,我僅獲得前4個內核的使用率達到50%,而后4個內核的使用率達到25%。 我如何通過python來使所有8個內核的使用率達到100%?

這樣的事情會讓您入門。 您需要調整num_processes才能匹配您的硬件。

import multiprocessing as mp
import time

def slow_func():
    while True:
        for i in xrange(99999):
            j = i*i

def main():
    num_processes = 4

    for _ in range(num_processes):
        process = mp.Process(target = slow_func)
        process.daemon = True
        process.start()

    while True:
        time.sleep(1)

if __name__ == '__main__':
    main()

編輯:這對具有4核的Windows而言對我有效,並提供4x 25%的處理器使用率。

要與線程模塊進行比較,您可以import threading並將process = mp.Process(target = slow_func)行替換為process = threading.Thread(target = slow_func) 您應該發現它僅使用您的一個核心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM