Show the execution time of any query in ColdFusion 8
I was working on some code today where I was getting back a query object from a CFC and needed to get the execution time. You can get this information from the <cfquery /> tag by using the result attribute, but since I was getting my query object back from a CFC, I needed to try and determine the execution time from only the query object.
Since the <cfdump /> tag is outputs additional meta data about a query (including the executionTime,) I knew this information could be obtained if I could just find the correct internal Java methods to call. After playing around for a few minutes I discovered that the additional struct keys that ColdFusion 8's <cfdump /> tag outputs come from: query.getMetaData().getExtendedMetaData().
So, to grab the execution time of any query in your code, you can just use:
Since I was using this information on a search results page, I wanted to show the execution time in seconds to the user (carried out to the 3rd decimal.) Because query's can often return a 0ms execution time (either because of timing issues on Windows or due to cached queries,) I came up with the following code to show the execution time in seconds. I use the min() function to at least show a 1ms execution time (since 0ms time just looks weird.)
#numberFormat(max(GetCustomers.getMetaData().getExtendedMetaData().executionTime, 1)/1000, "0.000")# seconds
</cfoutput>
The obvious disclaimer here is that since we're using internal methods, this can change in future versions of ColdFusion—which means your code could break.

Comments
<cfquery name="read" datasource="dns" result="stats">
</cfquery>
then you can simply refer to the stats.executiontime variable.
In my case, that wasn't an option because I had a query being returned from a CFC I didn't have control over. I posted this as a solution for getting the execution time when all you have is the query object.
Couldn't you return a structure of both the query and the result?
Dan had no control over the method returning the query so couldn't simply return a struct. Also this could have had repercussions on the rest of the system (API's or other local calls to that method etc).
Intresting.