view sched/HRTimer.java @ 61:eff6bddf82e3 tip

Finally implemented perceptual brightness thing.
author samer
date Sun, 11 Oct 2015 10:20:42 +0100
parents 7357e1dc2ad6
children
line wrap: on
line source

package saml.sched;

public class HRTimer {

	private static long min_sleep=1200000; // 1.2 ms
	private static long wake_before=500000; // 0.5ms

	public static void setMinimumSleepTime(long t) { min_sleep=t; }
	public static void setWakePrealarm(long t) { wake_before=t; }

	public static long now() { return System.nanoTime(); }
	public static long sleepUntil(long t1) throws Exception {
		long t0=System.nanoTime();
		long dt=t1-t0;
		// System.out.println("need to wait for " + dt +"ns");
		if (dt>min_sleep) {
			long sleep_time=dt-wake_before;
			long millis=sleep_time/1000000;
			int  nanos=(int)(sleep_time-millis*1000000);
			// System.out.println("will sleep for "+millis+"ms + "+nanos+"ns");
			Thread.sleep(millis,nanos); 
		}

		// go into a tight loop for the last few microseconds
		t0=System.nanoTime();
		// System.out.println("need to spin for "+(t1-t0)+"ns");
		while (t0<t1) t0=System.nanoTime();
		return t0-t1;
	}
	
	public static long estimateMinSleep() throws Exception {
		long t0,t1;

		t0=System.nanoTime();
		Thread.sleep(0,1); 
		t1=System.nanoTime();
		return t1-t0;
	}

	public static long estimateGranularity() {
		long t0, t1;
		t0=System.nanoTime();
		t1=System.nanoTime();
		return t1-t0;
	}
};