Skip to content

Instantly share code, notes, and snippets.

@maduraimad
Forked from bdkosher/timeIt.groovy
Last active September 27, 2018 12:52
Show Gist options
  • Save maduraimad/9f092c31634ecef399ee to your computer and use it in GitHub Desktop.
Save maduraimad/9f092c31634ecef399ee to your computer and use it in GitHub Desktop.
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
def (sumIt, msIt) = timeIt{ obj -> obj?.toString() + " as " + obj?.getClass()} {
1e12 + 1e12
} // assigns the result of the closure to sum and the elapsed time to ms; prints in the modified result fomat which also includes the class of the result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment