import time from concurrent import futures def sum_range(start, end): total = 0 for i in range(start, end): total += i return total if __name__ == '__main__': start_time = time.time() with futures.ProcessPoolExecutor(2) as executor: task1 = executor.submit(sum_range,1,50000001) task2 = executor.submit(sum_range,50000001,100000001) result = [task1.result(), task2.result()] total = sum(result) end_time = time.time() print("并行总和为:", total) print("并行用时:", end_time - start_time, "秒") start_time = time.time() result = sum_range(1,100000001) end_time = time.time() print("串行总和为:", result) print("串行用时:", end_time - start_time, "秒")给上述代码添加中文注释
时间: 2024-02-14 16:20:15 浏览: 23
import time
from concurrent import futures
# 定义一个计算某一范围内整数和的函数
def sum_range(start, end):
total = 0
# 遍历范围内的整数并相加
for i in range(start, end):
total += i
return total
if __name__ == '__main__':
start_time = time.time()
# 创建一个进程池,最多同时执行2个进程
with futures.ProcessPoolExecutor(2) as executor:
# 将任务1和任务2提交到进程池中并执行
task1 = executor.submit(sum_range,1,50000001)
task2 = executor.submit(sum_range,50000001,100000001)
# 获取任务1和任务2的结果并相加
result = [task1.result(), task2.result()]
total = sum(result)
end_time = time.time()
# 输出并行计算结果和用时
print("并行总和为:", total)
print("并行用时:", end_time - start_time, "秒")
start_time = time.time()
# 直接调用函数计算整数和
result = sum_range(1,100000001)
end_time = time.time()
# 输出串行计算结果和用时
print("串行总和为:", result)
print("串行用时:", end_time - start_time, "秒")
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)