Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created September 18, 2013 12:23
Show Gist options
  • Save bdkosher/6608422 to your computer and use it in GitHub Desktop.
Save bdkosher/6608422 to your computer and use it in GitHub Desktop.
Closure which can be used to time how long operations took.
def timeIt = { resultFormatter = { obj -> obj?.toString() }, closure ->
def start = System.nanoTime()
def result = null
try {
result = closure()
} catch (Exception e) {
result = e
}
def end = System.nanoTime()
def ms = (end - start) / 1e6
if (resultFormatter) {
println "Result ${resultFormatter(result)} obtained in $ms ms"
}
[result, ms]
}
// Usage is simple
timeIt {
1e12 + 1e12
} // prints 'Result 2E+12 obtained in 135.026656 ms'
def (sum, ms) = timeIt(null) {
1e12 + 1e12
} // assigns the result of the closure to sum and the elapsed time to ms; null arg suppresses the println
@maduraimad
Copy link

Apparently, pull requests are not supported on Gists yet...

My fork with passing a different resultFormatter
https://gist.github.com/maduraimad/9f092c31634ecef399ee

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment