Created
September 18, 2013 12:23
-
-
Save bdkosher/6608422 to your computer and use it in GitHub Desktop.
Closure which can be used to time how long operations took.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Apparently, pull requests are not supported on Gists yet...
My fork with passing a different resultFormatter
https://gist.github.com/maduraimad/9f092c31634ecef399ee