diff --git a/2020.06.01_parallel_calculations_with_python/application_of_parallel_calculations_with_python.py b/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_application.py similarity index 100% rename from 2020.06.01_parallel_calculations_with_python/application_of_parallel_calculations_with_python.py rename to 2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_application.py diff --git a/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_for_loop.py b/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_for_loop.py new file mode 100644 index 0000000..13c290c --- /dev/null +++ b/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_for_loop.py @@ -0,0 +1,31 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4536 +""" + +import multiprocessing +import os +import time + +def run_proc(name): # 要执行的代码 + start_time = time.perf_counter() + time.sleep(2) + end_time = time.perf_counter() + print ('Process id running on %s = %s' % (name, os.getpid()), '; running time = %s' % (end_time-start_time)) + +if __name__ == '__main__': + start_time = time.perf_counter() + + # 循环创建进程 + processes = [] + for i in range(4): + p = multiprocessing.Process(target=run_proc, args=(f'job{i}',)) + processes.append(p) + p.start() + + # 等待所有进程完成 + for p in processes: + p.join() + + end_time = time.perf_counter() + print('运行时间(s)=', (end_time-start_time)) \ No newline at end of file diff --git a/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_using_Pool.py b/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_using_Pool.py new file mode 100644 index 0000000..21a5274 --- /dev/null +++ b/2020.06.01_parallel_calculations_with_python/parallel_calculations_with_python_using_Pool.py @@ -0,0 +1,21 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/4536 +""" + +import multiprocessing +import os +import time + +def run_proc(name): + start_time = time.perf_counter() + time.sleep(2) + end_time = time.perf_counter() + print ('Process id running on %s = %s' % (name, os.getpid()), '; running time = %s' % (end_time-start_time)) + +if __name__ == '__main__': + start_time = time.time() + with multiprocessing.Pool() as pool: + results = pool.map(run_proc, range(64)) + end_time = time.time() + print(end_time - start_time) \ No newline at end of file