Skip to content

Commit

Permalink
helios: linux sleeps now considering timer slack
Browse files Browse the repository at this point in the history
  • Loading branch information
Federico Berti committed Nov 8, 2023
1 parent 499a589 commit 3f9dd13
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/main/java/omegadrive/util/Sleeper.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
public class Sleeper {

public static final boolean BUSY_WAIT;
public static final long SLEEP_LIMIT_NS = 10_000;

//Linux has a timer slack of 50micros, windows is hopeless
//https://lwn.net/Articles/369549/
public static final long SLEEP_RESOLUTION_NS = 50_000;
private final static Logger LOG = LogHelper.getLogger(Util.class.getSimpleName());

static {
Expand Down Expand Up @@ -51,11 +54,17 @@ private static void handleSlowdown(String when, long now, long deadlineNs) {

//sleeps for the given interval, doesn't mind returning a bit early
public static void parkFuzzy(final long intervalNs) {
parkExactly(intervalNs - SLEEP_LIMIT_NS);
if (intervalNs < SLEEP_RESOLUTION_NS) {
return;
}
parkExactly(intervalNs - SLEEP_RESOLUTION_NS);
}

public static void parkExactly(final long intervalNs) {
public static void parkExactly(long intervalNs) {
assert intervalNs > 0;
if (intervalNs < SLEEP_RESOLUTION_NS) {
return;
}
if (BUSY_WAIT) {
long deadlineNs = System.nanoTime() + intervalNs;
while (System.nanoTime() < deadlineNs) {
Expand All @@ -72,7 +81,9 @@ public static void parkExactly(final long intervalNs) {
}
do {
LockSupport.parkNanos(intervalNs);
done = System.nanoTime() > deadlineNs;
long nowNs = System.nanoTime();
intervalNs = Math.max(deadlineNs - intervalNs, SLEEP_RESOLUTION_NS);
done = nowNs > deadlineNs;
} while (!done);
handleSlowdown("After", System.nanoTime(), deadlineNs);
}
Expand Down

0 comments on commit 3f9dd13

Please sign in to comment.