创建一个python代码,该代码计算范围(3000000)内的素数,用于循环多线程(例如,如果Nthreads是N,它将



我正试图运行这个程序,但它向我显示了"线程0具有0个素数";在控制台中;被杀死";5分钟后。此外,它非常缓慢。请帮助我开发和更正此代码

import time
Nthreads=4
maxNumber=3000000
starting_range=0 
ending_range=0
division=0
lst=[]
def prime(x, y):
prime_list = []
for i in range(x, y):
if i == 0 or i == 1:
continue
else:
for j in range(2, int(i/2)+1):
if i % j == 0:
break
else:
prime_list.append(i)
return prime_list


def func_thread(x, y):
out.append(prime(x, y))
thread_list = []
results = len(lst)
for i in range(Nthreads):
devision=maxNumber//Nthreads
starting_range = (i-1)*division+1
ending_range = i*devision
lst = prime(starting_range, ending_range)
print(" Thread ", i, " has ", len(lst), " prime numbers." )
thread = threading.Thread(target=func_thread, args=(i, results))
thread_list.append(thread)
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()```

在Python中,如果对CPU绑定的任务使用多线程,则速度会比不使用多线程慢。对于这个问题,您需要使用多处理。你可以阅读这篇文章了解更多信息:https://www.geeksforgeeks.org/difference-between-multithreading-vs-multiprocessing-in-python/

多线程完全不适合这样的CPU密集型工作。然而,它是可以做到的:

from concurrent.futures import ThreadPoolExecutor
NTHREADS = 4
MAXNUMBER = 3_000_000
CHUNK = MAXNUMBER // NTHREADS
assert MAXNUMBER % NTHREADS == 0
RANGES = [(base, base+CHUNK) for base in range(0, MAXNUMBER, CHUNK)]
all_primes = []
def isprime(n):
if n <= 3:
return n > 1
if not n % 2 or not n % 3:
return False
for i in range(5, int(n**0.5)+1, 6):
if not n % i or not n % (i + 2):
return False
return True
def process(_range):
lo, hi = _range
if lo < 3:
all_primes.append(2)
lo = 3
elif lo % 2 == 0:
lo += 1
for p in range(lo, hi, 2):
if isprime(p):
all_primes.append(p)
with ThreadPoolExecutor() as executor:
executor.map(process, RANGES)

all_primes列表是无序的。还要注意,只有当MAXNUMBER可以被NTHREADS完全整除时,此策略才会起作用。

性能说明:

这在我的机器上需要7.88秒。多处理变体需要2.90s的

相关内容

  • 没有找到相关文章

最新更新