나는 사이트의 도메인 이름을 열거하기 위해 사용되는 파이썬 프로그램을 작성 중이다. 예를 들어, 'a.google.com'.asyncio 라이브러리가이 I/O 바인딩 작업의 스레드보다 느린 이유는 무엇입니까?
첫째,이 작업을 수행 할 threading
모듈을 사용 :
import string
import time
import socket
import threading
from threading import Thread
from queue import Queue
'''
enumerate a site's domain name like this:
1-9 a-z + .google.com
1.google.com
2.google.com
.
.
1a.google.com
.
.
zz.google.com
'''
start = time.time()
def create_host(char):
'''
if char is '1-9a-z'
create char like'1,2,3,...,zz'
'''
for i in char:
yield i
for i in create_host(char):
if len(i)>1:
return False
for c in char:
yield c + i
char = string.digits + string.ascii_lowercase
site = '.google.com'
def getaddr():
while True:
url = q.get()
try:
res = socket.getaddrinfo(url,80)
print(url + ":" + res[0][4][0])
except:
pass
q.task_done()
NUM=1000 #thread's num
q=Queue()
for i in range(NUM):
t = Thread(target=getaddr)
t.setDaemon(True)
t.start()
for host in create_host(char):
q.put(host+site)
q.join()
end = time.time()
print(end-start)
'''
used time:
9.448670148849487
'''
나중에 내가 코 루틴이 빠르게 스레드보다 어떤 경우에 말했다, 책을 읽습니다. 그래서, asyncio
를 사용하도록 코드를 재 작성 :
import asyncio
import string
import time
start = time.time()
def create_host(char):
for i in char:
yield i
for i in create_host(char):
if len(i)>1:
return False
for c in char:
yield c + i
char = string.digits + string.ascii_lowercase
site = '.google.com'
@asyncio.coroutine
def getaddr(loop, url):
try:
res = yield from loop.getaddrinfo(url,80)
print(url + ':' + res[0][4][0])
except:
pass
loop = asyncio.get_event_loop()
coroutines = asyncio.wait([getaddr(loop, i+site) for i in create_host(char)])
loop.run_until_complete(coroutines)
end = time.time()
print(end-start)
'''
time
120.42313003540039
'''
왜 getaddrinfo
의 asyncio
버전이 너무 느린 무엇입니까? 코 루틴을 어떻게 든 오용하고 있습니까?
나는 시스템에서 성능 차이를 거의 볼 수 없습니다. thread 버전은 20 초이고 asyncio 버전은 24입니다.'getaddr' 메소드에서 print 문을 제거해보십시오. 성능면에서 큰 차이가 있습니까? Printing은 GIL을 해제하므로 많은 스레드가 동시에이를 처리 할 수 있지만 asyncio는 수행 할 수 없습니다. 시스템에서 인쇄 속도가 특히 느린 경우에는 속도 차이를 고려해야합니다. – dano