Created
March 28, 2016 20:19
-
-
Save thorntonrose/cb0ea80e26d2a127a1dc to your computer and use it in GitHub Desktop.
Time utility methods
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
class Time { | |
static final INSTANT_PATTERN = | |
~/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z(|[\-\+]{1}[0-9]{4})?/ | |
static timingEnabled = false | |
static console = true | |
private Time() {} | |
static toGregorianCalendar(Instant instant) { | |
instant ? GregorianCalendar.from(ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)) : null | |
} | |
static parseInstant(Map map) { | |
map ? Instant.ofEpochSecond(map.epochSecond as long).plusNanos(map.nano as long) : null | |
} | |
static isInstantMap(obj) { | |
obj && obj instanceof Map && obj.epochSecond && obj.nano | |
} | |
static isInstantPattern(String str) { | |
str ? (str =~ INSTANT_PATTERN).matches() : null | |
} | |
static durationMillis(Instant start, Instant end) { | |
(end.epochSecond - start.epochSecond) * 1000 + (end.nano - start.nano) / 1000000 | |
} | |
static timeIt(prefix, closure) { | |
if (timingEnabled) { | |
def result | |
def exception | |
def start = System.currentTimeMillis() | |
try { | |
result = closure() | |
} catch(Exception e) { | |
exception = e | |
} | |
def duration = System.currentTimeMillis() - start | |
def message = "$prefix: time: $duration ms" | |
if (console) { println message } | |
if (exception) { throw exception } | |
result | |
} else { | |
closure() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment