我试图熟悉asyncio,所以我决定编写一个数据库客户端。但是,性能与同步代码完全匹配。我敢肯定这是我对一个概念的误解。有人可以解释我在做什么吗?
请参见下面的代码示例:
class Connection:
def __init__(self, reader, writer, loop):
self.futures = deque()
# ...
self.reader_task = asyncio.async(self.recv_data(), loop=self.loop)
@asyncio.coroutine
def recv_data(self):
while 1:
try:
response = yield from self.reader.readexactly(4)
size, = struct.unpack('I', response)
response = yield from self.reader.readexactly(size)
# ...
future = self.futures.popleft()
if not future.cancelled():
future.set_result(response)
except Exception:
break
def send_data(self, data):
future = asyncio.Future(loop=self.loop)
self.futures.append(future)
self.writer.write(data)
return future
loop = asyncio.get_event_loop()
@asyncio.coroutine
def benchmark():
connection = yield from create_connection(loop=loop, ...)
for i in range(10000):
yield from connection.send_data(...)
s = time.monotonic()
loop.run_until_complete(benchmark())
e = time.monotonic()
print('Requests per second:', int(10000 / (e - s)))
提前致谢。
您的通话方式弄错了send_data
。现在,您已经拥有了:
@asyncio.coroutine
def benchmark():
connection = yield from create_connection(loop=loop, ...)
for i in range(10000):
yield from connection.send_data(...)
通过yield from
在for循环内使用,您可以等待future
返回的对象send_data
产生结果,然后再继续下一个调用。这使您的程序基本上是同步的。您要对进行所有调用send_data
,然后等待结果:
@asyncio.coroutine
def benchmark():
connection = yield from create_connection(loop=loop, ...)
yield from asyncio.wait([connection.send_data(..) for _ in range(10000)])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句