Get Time to first byte from API Groovy

109 views Asked by At

I am writing a script to get TTFB for an URL. This getResponseCode method gives me status code for the URL. What method or formula can I use to get TTFB after connection is established?

HttpURLConnection connection

    try {
        
            URL url = new URL('www.xyx.com')
            connection = (HttpURLConnection)url.openConnection()
            connection.setRequestMethod("GET")
            connection.connect()

            println(connection.getResponseCode())
        
    }
    catch(Exception ex) {
        return 0
    }
    finally {
        connection.disconnect()
                    } 
    
1

There are 1 answers

3
daggett On

The obvious way

long t0 = System.getTimeMillis()
connection.getInputStream()?.read()
long t1 = System.getTimeMillis()

long ttfb = t1 - t0

However I'm not sure about accuracy...