gevent 用法

485 阅读1分钟

例子:

import time
import gevent
from gevent.threadpool import ThreadPool


pool = ThreadPool(3)
start = time.time()
for _ in range(4):
    pool.spawn(time.sleep, 1)
gevent.wait()
delay = time.time() - start
print('Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: %.3fs' % delay)

运行结果:

3个线程执行4个睡1s的操作:

(1)第一次,3个睡1s。使用了3个线程,满了,耗时1s

(2)第二次,1个睡1s。使用1个线程,耗时1s

(3)中间切换需要0.00x秒。

(4)理论总共耗时(2+0.00x)秒。

Running "time.sleep(1)" 4 times with 3 threads. Should take about 2 seconds: 2.004s

Process finished with exit code 0