Reputation: 1888
I need to know time to load a webpage from internet. I do not need to show the page and definitely discard contents after it loads. So I am using this:
suspend fun TimeItTook(): Long {
val startTime: Long = System.currentTimeMillis()
var endTime: Long = 0
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(mContext)
val url = "https://www.google.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
endTime = System.currentTimeMillis() //It should get the time when response arrives
//print(response)
},
{ endTime = startTime }) //if fails result should be 0
// Add the request to the RequestQueue.
queue.add(stringRequest)
return endTime - startTime
}
Now the result is negative. Which means there is something wrong.
And also I need to know if there is a better way to know the time required to load a web page.
Upvotes: 0
Views: 150
Reputation: 19622
You're putting your request on the queue, and then immediately moving to the next line, which returns 0 - startTime
. When your request returns a response later, it works out endTime
but doesn't actually do anything with it - you could do print(endTime - startTime)
or something if you just want to see the result.
The trouble is Volley is meant as a way to perform async requests, meaning you can fire them off in the background, and you can carry on running the rest of your code without waiting for the result. But the way your code is written, you want to wait for the result, so you can work out the time and return it from your function. You want the request to be a synchronous, blocking one.
Here's a question with answers that use Volley's RequestFuture
s, which you can call get()
on and block until you get a response. If you're not even using the response, you might want to look at some basic request stuff like HttpURLConnection or OkHttp instead of Volley. Or you can just use your code as-is, but your callback code has take care of the reporting, calling another function to provide an update, setting some global variables other code can see, etc.
And your actual timing code is fine - Kotlin has a measureTimeMillis convenience function if you want, but what you're doing is pretty standard!
Upvotes: 1