0

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()
                    } 
    
Surbhi
  • 3
  • 3

1 Answers1

0

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...

daggett
  • 26,404
  • 3
  • 40
  • 56
  • Retrieving the stream (`getInputStream()`) probably shouldn't be done inside the timer. The same thing for the null check. – Jeff Scott Brown Jul 06 '21 at 23:28
  • Probably you are right. I would wrap it into @CompileStatic to minimize dynamic groovy latency. – daggett Jul 07 '21 at 04:15
  • "I would wrap it into @CompileStatic to minimize dynamic groovy latency." - If you did, I still think it makes sense to call `getInputStream()` and do any null checking before the timer starts. – Jeff Scott Brown Jul 07 '21 at 13:01