Skip to content

Instantly share code, notes, and snippets.

@spladug
Last active July 13, 2020 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spladug/91483032d410714e1d416467a476a1ad to your computer and use it in GitHub Desktop.
Save spladug/91483032d410714e1d416467a476a1ad to your computer and use it in GitHub Desktop.
"""Check the time penalty for checking socket liveliness"""
import errno
import gc
import socket
import time
import gevent.socket
ITERATIONS = 10_000
scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
def format_time(dt):
for scale, unit in scales:
if dt >= scale:
break
return "%.*g %s" % (3, dt / scale, unit)
def benchmark():
for sock_cls in [socket.socket, gevent.socket.socket]:
print(f"{sock_cls=}")
for timeout in [None, 0, 1.0]:
sock = socket.socket()
sock.connect(("google.com", 80))
sock.settimeout(timeout)
results = []
for _ in range(3):
gc.disable()
start = time.perf_counter()
for _ in range(ITERATIONS):
##### here's the actual guts of the implementation
original_timeout = sock.gettimeout()
try:
sock.settimeout(0)
try:
peeked_bytes = sock.recv(1, socket.MSG_PEEK)
except (socket.error, OSError) as exc:
if exc.errno == errno.EWOULDBLOCK:
continue
raise
finally:
sock.settimeout(original_timeout)
########################################
end = time.perf_counter()
elapsed = end - start
results.append(elapsed)
gc.enable()
elapsed = min(results)
per = format_time(elapsed / ITERATIONS)
print(f"{timeout=} elapsed={format_time(elapsed)} {per=}")
benchmark()
$ python --version
Python 3.8.2
$ pip freeze
gevent==20.6.2
greenlet==0.4.16
zope.event==4.4
zope.interface==5.1.0
$ python benchmark-isOpen.py
sock_cls=<class 'socket.socket'>
timeout=None elapsed=240 msec per='2.4 usec'
timeout=0 elapsed=234 msec per='2.34 usec'
timeout=1.0 elapsed=204 msec per='2.04 usec'
sock_cls=<class 'gevent._socket3.socket'>
timeout=None elapsed=198 msec per='1.98 usec'
timeout=0 elapsed=206 msec per='2.06 usec'
timeout=1.0 elapsed=199 msec per='1.99 usec'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment