Skip to content

Instantly share code, notes, and snippets.

@mabn
Last active July 15, 2017 12:42
Show Gist options
  • Save mabn/9587658d78d730917559cd61a274ea4f to your computer and use it in GitHub Desktop.
Save mabn/9587658d78d730917559cd61a274ea4f to your computer and use it in GitHub Desktop.
a clock with microsecond precision
@Slf4j
public class MicrosecondPrecisionClock implements Clock {
private static final long ONE_MINUTE_IN_NANOSECONDS = 60_000_000_000L;
private final long systemTimeOffsetNs;
private long lastWarningLoggedAt;
public MicrosecondPrecisionClock() {
systemTimeOffsetNs = System.currentTimeMillis() * 1_000_000 - System.nanoTime();
}
@Override
public long currentTimeMicros() {
long currentNano = System.nanoTime();
logInaccuracies(currentNano);
return (currentNano + systemTimeOffsetNs) / 1000;
}
private void logInaccuracies(long currentNano) {
long systemTimeNs = System.currentTimeMillis() * 1_000_000;
if (systemTimeNs > lastWarningLoggedAt + ONE_MINUTE_IN_NANOSECONDS) {
if (Math.abs(currentNano + systemTimeOffsetNs - systemTimeNs) > 250_000_000) {
log.warn("Detected significant difference between the clock based on nanoTime+offset = {} and currentTimeMillis={}",
currentNano + systemTimeOffsetNs,
systemTimeNs
);
lastWarningLoggedAt = systemTimeNs;
}
}
}
@Override
public long currentNanoTicks() {
return System.nanoTime();
}
@Override
public boolean isMicrosAccurate() {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment