Last active
December 19, 2023 18:38
-
-
Save RoseSecurity/c9606963eda325d1750984e59bd94a22 to your computer and use it in GitHub Desktop.
Measure the Time To First Byte (TTFB) of a website by DNS lookup, TCP connection, SSL connection, and document HTTP request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import requests | |
import time | |
# Measure the Time To First Byte (TTFB) of a website by DNS lookup, TCP connection, SSL connection, and document HTTP | |
# request. | |
# Reference: https://www.debugbear.com/docs/metrics/time-to-first-byte | |
def measure_ttfb(url): | |
try: | |
start_time = time.time() | |
response = requests.get(url) | |
dns_time = response.elapsed.total_seconds() | |
tcp_time = 0 | |
ssl_time = 0 | |
if response.url.startswith("https"): | |
ssl_time = response.elapsed.total_seconds() | |
document_time = time.time() - start_time | |
ttfb = dns_time + tcp_time + ssl_time + document_time | |
return ttfb, dns_time, tcp_time, ssl_time, document_time, response.status_code | |
except requests.exceptions.RequestException as e: | |
print(f"\033[91mError: {e}\033[0m") | |
return None, None, None, None, None, None | |
def main(): | |
url = input("Enter the URL of the website to measure TTFB: ") | |
ttfb, dns_time, tcp_time, ssl_time, document_time, status_code = measure_ttfb(url) | |
if ttfb is not None and status_code is not None: | |
print(f"\033[1m\033[92mDNS Lookup Time: \033[0m{dns_time:.3f} seconds") | |
print(f"\033[1m\033[92mTCP Connection Time: \033[0m{tcp_time:.3f} seconds") | |
if ssl_time > 1: | |
print(f"\033[1m\033[91mSSL Connection Time: \033[1m{ssl_time:.3f} seconds\033[0m") | |
else: | |
print(f"\033[1m\033[92mSSL Connection Time: \033[0m{ssl_time:.3f} seconds") | |
print(f"\033[1m\033[92mDocument HTTP Request Time: \033[0m{document_time:.3f} seconds") | |
print(f"\033[1m\033[92mHTTP Status Code: \033[0m{status_code}\033[0m") | |
else: | |
print("\033[91mFailed to measure TTFB.\033[0m") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment