-
-
Save maduraimad/9f092c31634ecef399ee to your computer and use it in GitHub Desktop.
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 | |
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