Python中的并行性和并发性(概念+代码)

嗨伙计 !! 希望所有编程爱好者都做得不错。 在本文中,我们将讨论python中的并发和并行性。 在这里,我们将研究多线程,多处理,异步编程,并发和并行性,以及如何使用这些概念来加快python中的计算任务。 因此,在不浪费时间的情况下,让我们开始吧。

[我已经假设您对python有一定的了解。 如果没有,我建议您在继续之前先阅读这篇文章:

https://hackernoon.com/pythonic-way-of-doing-things-code-kq2b430vv ]

并行性

这意味着要同时以相同的顺序执行多个任务。

1.多重处理:这意味着将任务分配到CPU内核上[在终端中键入<lscpu>来检查计算机中的内核数。 ]。 对于任何与CPU绑定的任务(例如进行数值计算),我们可以使用python的multiprocessing模块。 我们只是在多处理中创建一个Pool对象,它提供了一种方便的方法来跨多个输入值并行执行函数。 让我们借助一个示例来看看它:

import multiprocessing
import os 
import time 
import numpy as np

def DotProduct (A) :
    dot_product = np.dot(A[ 0 ],A[ 1 ])   
    return

 List = [[np.arange( 1000000 ).reshape( 5000 , 200 ),np.arange( 1000000 ).reshape( 200 , 5000 )],
         [np.arange( 1000000 ).reshape( 500 , 2000 ),np.arange( 1000000 ).reshape( 2000 , 500 )],
         [np.arange( 1000000 ).reshape( 5000 , 200 ),np.arange( 1000000 ).reshape( 200 , 5000 )]]
  
if __name__ == "__main__" :    
    # executing a code without multiprocessing .. ie. on single core . 
    start = time.time()
    B = list(map(DotProduct,List))
    end = time.time() - start
    print( "Full time taken : " , end , "seconds" )
    
    # lets look at executing same code with multiprocesing module on multiple cores ..  
    start = time.time()
    pool = multiprocessing.cpu_count() 
    with multiprocessing.Pool(pool) as p:
        print(p.map(DotProduct,List))
    end = time.time() - start
    print( "Full time taken : " , end , "seconds" )   

##输出//
全日制:23.593358993530273秒
全日制:14.405884027481079秒

并发

这意味着同时执行多个任务,但要以重叠或不同或相同的顺序进行。 (Python在处理并发方面不是很出色),但是它做得相当不错。

1.多线程:运行不同/多个线程以在单个处理器上执行任务。 多线程对于执行IO绑定任务(例如—同时向服务器发送多个请求等)确实非常有用。 创建的每个新线程将具有PID(进程ID),并将具有启动函数。 如果要在线程完成其工作后运行loc,可以使用线程的join()函数。 Python与它的GIL有非常复杂的关系,并且代码的输出变化很大。

2.异步IO:在Python中,异步IO是单线程单进程设计范例,以某种方式设法实现并发。

让我们借助一个示例对其进行研究。

import threading
import os 
import time 
import numpy as np

def BasicOperation () :
    # square of number 
    def square (number) :
        return number*number
    # cube of a number 
    def cube (number) :
        return number** 3
    # nth power of a number 
    def nth_power (number,power) :
        return number**power
    # sum of n numbers 
    def sum_of_n_numbers (number) :
        return number*(number+ 1 )/ 2  
    # using functions to drive a program ... 
    print( "square of 5 is " , square( 5 ))
    print( "cube of 5 is " , cube( 5 ))
    print( "5 raise to power 2 is " , nth_power( 5 , 2 ))
    print( "sum of first 5 numbers is" , sum_of_n_numbers( 5 ))
    
def DotProduct () :
    A = np.arange( 1000000 ).reshape( 5000 , 200 )
    B = np.arange( 1000000 ).reshape( 200 , 5000 )
    Dot = np.dot(A,B)

if __name__ == "__main__" :      
        # without threading ... 
        start = time.time()
        BasicOperation()
        Mid = time.time() - start
        print( "Mid time taken : " , Mid , "seconds" )
        DotProduct()
        end = time.time() - start
        print( "Full time taken : " , end , "seconds" )
        # with threading ... 
        start = time.time()
        Thread_1 = threading.Thread(target = BasicOperation, name = ' Basic Operation Thread ' ) 
        Thread_2 = threading.Thread(target = DotProduct , name= ' Dot Product Thread ' )
        Thread_1.start() 
        Thread_2.start() 
        Thread_1.join() 
        Mid = time.time() - start
        print( "Mid time taken : " , Mid , "seconds" ) 
        Thread_2.join()
        end = time.time() - start
        print( "Full time taken : " , end , "seconds" )

##输出//
5的平方是25
5的立方体是125
5提升至力量2是25
前5个数字的总和为15.0
耗时:0.0006113052368164062秒
全时间:5的平方是10.373110294342041 25秒

5的多维数据集是采取的中间时间:1250.0015938282012939453
5加电2秒
25
前5个数字的总和为15.0
全日制:12.598262786865234秒

摘要

我们使用python的多处理模块来实现并行性,而Python中的并发是通过线程和异步IO模块来实现的。 并行运行的程序将被称为并发程序,但反之则不成立。

而已。 感谢您抽出宝贵的时间阅读我的帖子。 我希望你喜欢它。

From: https://hackernoon.com/parallelism-and-concurrency-in-python-concept-code-3w75430wo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值