We use the normal synchronous method to scan 10 ports, and the coroutine (asynchronous) method to scan 1000 ports and compare the time.
1,Synchronization Method Code
# Encoding = UTF-8 # Author: Walker # Date: 2014-07-16 # function: Use Synchronous Scan of 10 ports import time, socket, sysdef task (ADDR): sock = socket. socket (socket. af_inet, socket. sock_stream) sock. setTimeout (100) Try: sock. connect (ADDR) print ('Port' + STR (ADDR [1]) + 'is open') failed T: passfinally: sock. close () # scan 10 ports def synchronous (): for I in range (0, 10): task ('123. 0.0.1 ', I) t0 = time. time () synchronous () T1 = time. time () print ('time: {} s '. format (T1-T0 ))
The test result of the Walker machine is9.0110001564 s ≈ 9 s.
2,Coroutine (asynchronous) Code
# Encoding = UTF-8 # Author: Walker # Date: 2014-07-16 # function: Use coroutine (asynchronous) to scan 1000 port import gevent. monkeygevent. monkey. patch_socket () Import gevent, socket, sys, timedef task (ADDR): sock = socket. socket (socket. af_inet, socket. sock_stream) sock. setTimeout (100) Try: sock. connect (ADDR) print ('Port' + STR (ADDR [1]) + 'is open') failed T: passfinally: sock. close () # scan 1000 ports def asynchronous (): threads = [] For I in range (0, 1000): threads. append (gevent. spawn (task, ('2014. 127. 0.0.1 ', I) gevent. joinall (threads) t0 = time. time () asynchronous () T1 = time. time () print ('time: {} s '. format (T1-T0 ))
The test result of the Walker machine is2.08499979973 s ≈ 2 S.
It takes 9 s to scan 10 ports in synchronous mode, and 2 S to scan 1000 ports in coroutine mode! In terms of Code complexity, the asynchronous function only has one more row than the synchronous function.That is to sayCoroutine achieves the performance of asynchronous programs with Code complexity in synchronous mode!
To use gevent in windows, we recommend that you install the binary version, install greenlet first, and then install gevent:
Http://www.lfd.uci.edu /~ Gohlke/pythonlibs/# greenlet
Http://www.lfd.uci.edu /~ Gohlke/pythonlibs/# gevent
Refer:Gevent tutorial Chinese Translation
* ** Walker ***
This article is from the "Walker's journal account" blog, please be sure to keep this source http://walkerqt.blog.51cto.com/1310630/1439034