python异步执行_测试python同步异步执行方式

本文通过一个简单的例子对比了同步与异步执行方式的区别,包括多线程、多进程及协程等不同并发编程技术的实现与性能表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值