请写一段高性能多线程的代码
时间: 2024-02-24 17:56:51 浏览: 50
多线程代码
好的,以下是一个使用多线程实现高性能的计算素数的示例代码:
```python
import threading
import time
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def find_primes(start, end, results):
primes = []
for i in range(start, end):
if is_prime(i):
primes.append(i)
results[start] = primes
def main():
num_threads = 4
results = [[] for _ in range(num_threads)]
max_num = 100000
chunk_size = max_num // num_threads
threads = []
start_time = time.time()
for i in range(num_threads):
start = i * chunk_size
end = (i + 1) * chunk_size
thread = threading.Thread(target=find_primes, args=(start, end, results))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
primes = []
for i in range(num_threads):
primes.extend(results[i])
print("Found {} primes in {} seconds".format(len(primes), time.time() - start_time))
if __name__ == "__main__":
main()
```
这个程序将一个大的素数范围分成多个块,每个块在单独的线程中计算素数。每个线程的结果存储在一个共享的列表中。主线程等待所有线程完成后,合并所有结果并输出总素数数量和计算时间。这个程序的性能比单线程版本要好很多,因为它可以同时利用多个CPU核心来进行计算。
阅读全文