測試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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM