use futures::executor::block_on;
asyncfnhello_world() {
println!("hello, world!");
}
fnmain() {
let future = hello_world(); // Nothing is printed
block_on(future); // `future` is run and "hello, world!" is printed
}
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with requests.Session() as session:
for _ inrange(100):
fetch(session, URL)
进程/线程/协程性能比较
多进程:7秒
from multiprocessing.pool import Pool
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with Pool() as pool:
with requests.Session() as session:
pool.starmap(fetch, [(session, URL) for _ inrange(100)])
进程/线程/协程性能比较
线程:4秒
from concurrent.futures import ThreadPoolExecutor
import requests
from timer import timer
URL = 'https://httpbin.org/uuid'deffetch(session, url):with session.get(url) as response:
print(response.json()['uuid'])
@timer(1, 1)defmain():with ThreadPoolExecutor(max_workers=100) as executor:
with requests.Session() as session:
executor.map(fetch, [session] * 100, [URL] * 100)
executor.shutdown(wait=True)
进程/线程/协程性能比较
协程:2秒
...
URL = 'https://httpbin.org/uuid'asyncdeffetch(session, url):asyncwith session.get(url) as response:
json_response = await response.json()
print(json_response['uuid'])
asyncdefmain():asyncwith aiohttp.ClientSession() as session:
tasks = [fetch(session, URL) for _ inrange(100)]
await asyncio.gather(*tasks)
@timer(1, 1)deffunc():
asyncio.run(main())