zoukankan      html  css  js  c++  java
  • 测试python同步异步执行方式

    1. 代码

    import time 
    import asyncio 
    from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
    
    def job(num):
        print(f'job {num}: start...')
        time.sleep(num)
        print(f'job {num}: end ...')
    
    
    def elasped(func, num, s):
        print('-'*3, s, '-'*3)
        t0 = time.time()
        func(num)
        print(f'Complished in {time.time()-t0:.2f}s')
    
    def sync(num):
        for i in range(1, num):
            job(i)
    
    def thread_async(num):
        workers = num 
        with ThreadPoolExecutor(workers) as executor: 
            executor.map(job, range(1, num))
    
    def process_async(num):
        workers = num 
        with ProcessPoolExecutor(workers) as executor: 
            executor.map(job, range(1, num))
    
    async def coroutine_async(num):
        async def job(num):
            print(f'job {num}: start...')
            await asyncio.sleep(num)
            print(f'job {num}: end ...')
    
        await asyncio.gather(*[job(i) for i in range(1, num)])
    
    def elasped2(func, num, s):
        print('-'*3, s, '-'*3)
        t0 = time.time()
        asyncio.run(func(num))
        print(f'Complished in {time.time()-t0:.2f}s')
        
    
    
    if __name__ == '__main__':
        elasped(sync, 4, '同步执行') 
        elasped(thread_async, 4, '异步执行(多线程)')
        elasped(process_async, 4, '异步执行(多进程)')
        elasped2(coroutine_async, 4, '异步执行(协程)')
    

    2. 结果

    --- 同步执行 ---
    job 1: start...
    job 1: end ...
    job 2: start...
    job 2: end ...
    job 3: start...
    job 3: end ...
    Complished in 6.00s
    --- 异步执行(多线程) ---
    job 1: start...
    job 2: start...
    job 3: start...
    job 1: end ...
    job 2: end ...
    job 3: end ...
    Complished in 3.00s
    --- 异步执行(多进程) ---
    job 1: start...
    job 2: start...
    job 3: start...
    job 1: end ...
    job 2: end ...
    job 3: end ...
    Complished in 3.03s
    --- 异步执行(协程) ---
    job 1: start...
    job 2: start...
    job 3: start...
    job 1: end ...
    job 2: end ...
    job 3: end ...
    Complished in 3.00s
    
  • 相关阅读:
    spring复杂数据类型传递
    spring表单—乱码解决方案
    spring重定向与转发
    线程在WPF中的使用
    xheditor编辑器上传截图图片抓取远程图片代码
    js window.open()弹出窗口参数说明及居中设置
    INFORMATION_SCHEMA.COLUMNS 查询表字段语句
    SQL 使用Cursor(游标)遍历结果集
    js禁止浏览器滚屏方法
    基础-ADO插入数据后返回自增ID @@IDENTITY
  • 原文地址:https://www.cnblogs.com/lyg-blog/p/13583648.html
Copyright © 2011-2022 走看看