Skip to content

Instantly share code, notes, and snippets.

@fagci
Created September 22, 2021 18:02
Show Gist options
  • Save fagci/cfa48d0f9b96661c90651bd088ebc67e to your computer and use it in GitHub Desktop.
Save fagci/cfa48d0f9b96661c90651bd088ebc67e to your computer and use it in GitHub Desktop.
Measure TTFB using python
#!/usr/bin/env python3
from socket import gethostbyname, socket
from ssl import wrap_socket
from sys import argv
from time import time
from urllib.parse import urlparse
def main(url):
pu = urlparse(url)
port = pu.port or (80 if pu.scheme == 'http' else 443)
t_start = time()
host = gethostbyname(pu.hostname)
t_dns = time()
with socket() as _s:
s = wrap_socket(_s) if pu.scheme == 'https' else _s
s.connect((host, port))
t_connect = time()
s.send(('GET %s HTTP/1.1\r\n'
'Host: %s\r\n'
'User-Agent: Mozilla/5.0\r\n'
'\r\n').encode())
s.recv(1)
t_tfb = time()
print('TTFB', round((t_tfb - t_start) * 1000), 'ms')
print('DNS', round((t_dns - t_start) * 1000), 'ms')
print('CONN', round((t_connect - t_dns) * 1000), 'ms')
if __name__ == '__main__':
main(argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment