import time
from concurrent import futures
def cpu_bound(number):
return sum(i * i for i in range(number))
def calculate_sums(numbers):
for number in numbers:
print(cpu_bound(number))
def main():
start_time = time.perf_counter()
numbers = [10000000 + x for x in range(20)]
calculate_sums(numbers)
end_time = time.perf_counter()
print('Calculation takes {} seconds'.format(end_time - start_time))
def main_process():
start_time = time.perf_counter()
numbers = [10000000 + x for x in range(20)]
with futures.ProcessPoolExecutor() as pe:
result = pe.map(cpu_bound, numbers)
print(f"result: {list(result)}")
end_time = time.perf_counter()
print('multiprocessing Calculation takes {} seconds'.format(end_time - start_time))
if __name__ == '__main__':
main()
main_process()
————————
输出:
333333283333335000000
333333383333335000000
333333483333355000001
333333583333395000005
333333683333455000014
333333783333535000030
333333883333635000055
333333983333755000091
333334083333895000140
333334183334055000204
333334283334235000285
333334383334435000385
333334483334655000506
333334583334895000650
333334683335155000819
333334783335435001015
333334883335735001240
333334983336055001496
333335083336395001785
333335183336755002109
Calculation takes 15.771127400000001 seconds
result: [333333283333335000000, 333333383333335000000, 333333483333355000001, 333333583333395000005, 333333683333455000014, 333333783333535000030, 333333883333635000055, 333333983333755000091, 333334083333895000140, 333334183334055000204, 333334283334235000285, 333334383334435000385, 333334483334655000506, 333334583334895000650, 333334683335155000819, 333334783335435001015, 333334883335735001240, 333334983336055001496, 333335083336395001785, 333335183336755002109]
multiprocessing Calculation takes 4.7333084 seconds
展开