मैं एक पाइथन प्रोग्राम लिख रहा हूं जो किसी साइट के डोमेन नाम की गणना करने के लिए उपयोग किया जाता है। उदाहरण के लिए, 'a.google.com'।इस आई/ओ-बाउंड ऑपरेशन के लिए थ्रेड की तुलना में एसिन्सीओ लाइब्रेरी धीमी क्यों है?
पहले, मैं यह करने के लिए 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
'''
बाद में, मैं एक किताब जो कुछ मामलों coroutines तेजी से धागे से कर रहे हैं में कहा पढ़ें। तो, मैं 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
संस्करण इतनी धीमी गति से है? क्या मैं किसी भी तरह coroutines का दुरुपयोग कर रहा हूँ?
मुझे अपने सिस्टम पर लगभग एक प्रदर्शन अंतर दिखाई नहीं दे रहा है। थ्रेडेड संस्करण 20 सेकंड था, asyncio संस्करण 24 था। 'Getaddr' विधि से प्रिंट स्टेटमेंट को हटाने का प्रयास करें। क्या यह प्रदर्शन में एक बड़ा अलग बनाता है? प्रिंटिंग जीआईएल जारी करती है, इतने सारे थ्रेड एक साथ ऐसा कर सकते हैं, जबकि 'asyncio' नहीं कर सकता है। यदि प्रिंटिंग आपके सिस्टम पर विशेष रूप से धीमी है, तो यह गति अंतर के लिए जिम्मेदार हो सकती है। – dano